---
title: "Cloud Functions のアクセス制御 | grasys blog"
url: "https://blog.grasys.io/post/higuchi/gcf-auth/"
description: "○リカリさんのGCP記事って助かりますよね。 「その記事、知ってます!!」と話がスムーズに流れたり。 \\[参考\\] Google Cloud (GCP) Functionsの関数コール権をIAMで管理するためのテクニック https://tech.mercari.com/entry/2019/03/28/171100…"
---

# Cloud Functions のアクセス制御

-   ![](/_astro/noicon.CTHOhNiB_1HMs6A.webp)[higuchi](/authors/higuchi/)
-   公開日：2019年10月26日
-   カテゴリー：[Tech](/categories/tech/)
-   タグ：[#Cloud Functions](/tags/cloud-functions/)[#Cloud Storage](/tags/cloud-storage/)

![Cloud Functions のアクセス制御](/_astro/og-image.DDSiu2Ny_XHpDd.webp)

○リカリさんのGCP記事って助かりますよね。  
「その記事、知ってます!!」と話がスムーズに流れたり。

\[参考\] Google Cloud (GCP) Functionsの関数コール権をIAMで管理するためのテクニック  
[https://tech.mercari.com/entry/2019/03/28/171100](https://tech.mercari.com/entry/2019/03/28/171100)

記事はGo版のサンプルなので、Python版を書いてみます。

Cloud Functions (Python 3.7)

Plain textcontent\_copy

```
def IsAuthorized(token):
    credentials = google.oauth2.credentials.Credentials(token)
    client = storage.Client('{project_id}', credentials)
    bucket = storage.Bucket(client, '{bucket_name}')
    authorizedPermission = bucket.test_iam_permissions(
        ["storage.buckets.get"], client)
    return len(authorizedPermission) > 0

def main(req):
    try:
        if "Authorization" not in req.headers:
            raise SystemError("Authorization Head Not Found")
        if IsAuthorized(req.headers['Authorization']) is False:
            raise FileNotFoundError("Not Authenticated")
```

* * *

それではリクエストの準備をしましょう。

GCPパートナーらしく、GCPコンソールの操作ではなく、 gcloud コマンドでやる事にします。(らしいのか・・)

GCSにBucketを作成

Plain textcontent\_copy

```
gsutil mb -l asia-northeast1 gs://{bucket_name}
```

サービスアカントを作成

Plain textcontent\_copy

```
gcloud beta iam service-accounts create gcf-auth --description "GCF認証用" --display-name "GCF-Auth"
```

GCSのBucketのACLにREADERでサービスアカウントを追加

Plain textcontent\_copy

```
gsutil acl ch -u gcf-auth@{project_id}.iam.gserviceaccount.com:R gs://{bucket_name}
```

サービスアカウントの鍵を作成

Plain textcontent\_copy

```
gcloud beta iam service-accounts keys create gcf-auth.json --iam-account gcf-auth@{project_id}.iam.gserviceaccount.com
```

鍵からTokenを発行

Plain textcontent\_copy

```
GOOGLE_APPLICATION_CREDENTIALS=./gcf-auth.json gcloud auth application-default print-access-token
```

* * *

準備が出来たので関数にリクエストをします。

Plain textcontent\_copy

```
curl -X POST https://asia-northeast1-{project_id}.cloudfunctions.net/{function_name} -H "Authorization: "$GOOGLE_APPLICATION_CREDENTIALS
```

これにて終了です。  
これからも良い記事をお願いします。

## この記事を書いた人

[![](/_astro/noicon.CTHOhNiB_Z24aAgM.webp)](/authors/higuchi/)

### [higuchi](/authors/higuchi/)

higuchiのプロフィールと執筆記事をご覧いただけます。

[プロフィールと記事一覧](/authors/higuchi/)
