Auth0でGoogle Cloud Endpointsをセキュリティ保護する

Google Cloud Endpoints(GCE)は、APIの作成、維持、およびセキュリティ保護などの機能を提供するAPI管理システムです。GCEはOpenAPIを使用して、APIのエンドポイント、入出力、エラー、およびセキュリティ記述を定義します。

OpenAPI仕様の詳細については、GitHubのOpenAPI Specification(OpenAPIの仕様)リポジトリを参照してください。

このチュートリアルでは、Auth0を使用してGoogle Cloud Endpointsをセキュリティ保護する方法を説明します。

前提条件

開始する前に、GCE APIをデプロイしておく必要があります。まだAPIを作成していない場合は、Googleドキュメントにある「Cloud Endpointsのクイックスタート」を読み、作業を完了させます。

このクイックスタートでは、3文字のIATAコードから空港名を返す/airportNameという単一のエンドポイントを持つ簡単なGCE APIを作成する手順を説明しています。


curl --request GET \
  --url 'https://%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO'

Was this helpful?

/
var client = new RestClient("https://%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO");
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);

Was this helpful?

/
package main

import (
	"fmt"
	"net/http"
	"io/ioutil"
)

func main() {

	url := "https://%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO"

	req, _ := http.NewRequest("GET", url, nil)

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := ioutil.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}

Was this helpful?

/
HttpResponse<String> response = Unirest.get("https://%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO")
  .asString();

Was this helpful?

/
var axios = require("axios").default;

var options = {
  method: 'GET',
  url: 'https://%7ByourGceProject%7D.appspot.com/airportName',
  params: {iataCode: 'SFO'}
};

axios.request(options).then(function (response) {
  console.log(response.data);
}).catch(function (error) {
  console.error(error);
});

Was this helpful?

/
#import <Foundation/Foundation.h>

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO"]
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:10.0];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                if (error) {
                                                    NSLog(@"%@", error);
                                                } else {
                                                    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                                                    NSLog(@"%@", httpResponse);
                                                }
                                            }];
[dataTask resume];

Was this helpful?

/
$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "https://%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

Was this helpful?

/
import http.client

conn = http.client.HTTPSConnection("")

conn.request("GET", "%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO")

res = conn.getresponse()
data = res.read()

print(data.decode("utf-8"))

Was this helpful?

/
require 'uri'
require 'net/http'
require 'openssl'

url = URI("https://%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

request = Net::HTTP::Get.new(url)

response = http.request(request)
puts response.read_body

Was this helpful?

/
import Foundation

let request = NSMutableURLRequest(url: NSURL(string: "https://%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "GET"

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()

Was this helpful?

/

Auth0でAPIを定義する

[Auth0 Dashboard] > [Applications(アプリケーション)] > [APIs]に進み、新しいAPIを作成します。

Dashboard - APIの作成 - 統合 - Googleのエンドポイント

次のステップで使用するために、(上のスクリーンショットにあるhttp://google_api[API Audience(APIオーディエンス)]のIDをメモしておいてください。

API構成を更新する

次に、GCE API用のOpenAPI構成ファイルを更新します。クイックスタート中に作成されたサンプルAPIでは、このファイルはopenapi.yamlとなっています。

セキュリティ定義を追加する

この構成ファイルを開き、新しくsecurityDefinitionsセクションを追加します。このセクションに、以下のフィールドを持つ新しい定義(auth0_jwt)を追加します。

フィールド 説明
authorizationUrl 認可URLで、"https://{yourDomain}/authorize"に設定する必要があります。
flow OAuth2のセキュリティスキームで使用されるフローです。有効な値は"implicit""password""application""accessCode"です。
type セキュリティスキームの種類です。有効な値は"basic""apiKey""oauth2"です。
x-google-issuer 資格情報の発行者で、"https://{yourDomain}/"に設定する必要があります。
x-google-jwks_uri JSON Web Token(JWT)署名の検証に使用される公開鍵のURIです。これは"https://{yourDomain}/.well-known/jwks.json"に指定します。
x-google-audiences APIの識別子です。この値が、Auth0 DashboardでAPIに定義したものと一致することを確認してください。

codeblockOld.header.login.configureSnippet
securityDefinitions:
  auth0_jwt:
    authorizationUrl: "https://{yourDomain}/authorize"
    flow: "implicit"
    type: "oauth2"
    x-google-issuer: "https://{yourDomain}/"
    x-google-jwks_uri: "https://{yourDomain}/.well-known/jwks.json"
    x-google-audiences: "{yourApiIdentifier}"

Was this helpful?

/

エンドポイントを更新する

次に、前のステップで作成したsecurityDefinitionを使用してsecurityフィールドを追加し、エンドポイントを更新します。

paths:
  "/airportName":
    get:
      description: "Get the airport name for a given IATA code."
      operationId: "airportName"
      parameters:
        -
          name: iataCode
          in: query
          required: true
          type: string
      responses:
        200:
          description: "Success."
          schema:
            type: string
        400:
          description: "The IATA code is invalid or missing."
      security:
       - auth0_jwt: []

Was this helpful?

/

上の例では、securityフィールドがGCEプロキシに、/airportNameパスがauth0-jwtでセキュリティ保護されていることが期待されていることを伝えています。

OpenAPIの構成が更新されると、以下のようになります。

codeblockOld.header.login.configureSnippet
---
swagger: "2.0"
info:
  title: "Airport Codes"
  description: "Get the name of an airport from its three-letter IATA code."
  version: "1.0.0"
host: "{yourGceProject}.appspot.com"
schemes:
  - "https"
paths:
  "/airportName":
    get:
      description: "Get the airport name for a given IATA code."
      operationId: "airportName"
      parameters:
        -
          name: iataCode
          in: query
          required: true
          type: string
      responses:
        200:
          description: "Success."
          schema:
            type: string
        400:
          description: "The IATA code is invalid or missing."
      security:
       - auth0_jwt: []
securityDefinitions:
  auth0_jwt:
    authorizationUrl: "https://{yourDomain}/authorize"
    flow: "implicit"
    type: "oauth2"
    x-google-issuer: "https://{yourDomain}/"
    x-google-jwks_uri: "https://{yourDomain}/.well-known/jwks.json"
    x-google-audiences: "{yourApiIdentifier}"

Was this helpful?

/

APIを再デプロイする

次に、GCE APIを再デプロイして、構成変更を適用します。Cloud Endpointsのクイックスタートに従った場合は、GoogleのCloud Shellに以下を入力することで再デプロイすることができます。

cd endpoints-quickstart/scripts
./deploy_api.sh

Was this helpful?

/

APIをテストする

再デプロイが完了したら、セキュリティなしでAPIを再度呼び出します。


curl --request GET \
  --url 'https://%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO'

Was this helpful?

/
var client = new RestClient("https://%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO");
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);

Was this helpful?

/
package main

import (
	"fmt"
	"net/http"
	"io/ioutil"
)

func main() {

	url := "https://%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO"

	req, _ := http.NewRequest("GET", url, nil)

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := ioutil.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}

Was this helpful?

/
HttpResponse<String> response = Unirest.get("https://%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO")
  .asString();

Was this helpful?

/
var axios = require("axios").default;

var options = {
  method: 'GET',
  url: 'https://%7ByourGceProject%7D.appspot.com/airportName',
  params: {iataCode: 'SFO'}
};

axios.request(options).then(function (response) {
  console.log(response.data);
}).catch(function (error) {
  console.error(error);
});

Was this helpful?

/
#import <Foundation/Foundation.h>

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO"]
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:10.0];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                if (error) {
                                                    NSLog(@"%@", error);
                                                } else {
                                                    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                                                    NSLog(@"%@", httpResponse);
                                                }
                                            }];
[dataTask resume];

Was this helpful?

/
$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "https://%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

Was this helpful?

/
import http.client

conn = http.client.HTTPSConnection("")

conn.request("GET", "%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO")

res = conn.getresponse()
data = res.read()

print(data.decode("utf-8"))

Was this helpful?

/
require 'uri'
require 'net/http'
require 'openssl'

url = URI("https://%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

request = Net::HTTP::Get.new(url)

response = http.request(request)
puts response.read_body

Was this helpful?

/
import Foundation

let request = NSMutableURLRequest(url: NSURL(string: "https://%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "GET"

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()

Was this helpful?

/

以下のような応答が返されます。

{
 "code": 16,
 "message": "JWT validation failed: Missing or invalid credentials",
 "details": [
  {
   "@type": "type.googleapis.com/google.rpc.DebugInfo",
   "stackEntries": [],
   "detail": "auth"
  }
 ]
}

Was this helpful?

/

期待どおりの結果です。

次に、Auth0 DashboardのGoogle Endpoints API定義の[Test(テスト)]ページに移動し、[Response(応答)]の下にあるアクセストークンをコピーします。

Authorization Header(認可ヘッダー)にBearer {ACCESS_TOKEN}を設定し、APIに対してGET要求を実行することで、認可されたアクセスを取得します。


curl --request GET \
  --url 'https://%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO' \
  --header 'authorization: Bearer {accessToken}'

Was this helpful?

/
var client = new RestClient("https://%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO");
var request = new RestRequest(Method.GET);
request.AddHeader("authorization", "Bearer {accessToken}");
IRestResponse response = client.Execute(request);

Was this helpful?

/
package main

import (
	"fmt"
	"net/http"
	"io/ioutil"
)

func main() {

	url := "https://%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO"

	req, _ := http.NewRequest("GET", url, nil)

	req.Header.Add("authorization", "Bearer {accessToken}")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := ioutil.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}

Was this helpful?

/
HttpResponse<String> response = Unirest.get("https://%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO")
  .header("authorization", "Bearer {accessToken}")
  .asString();

Was this helpful?

/
var axios = require("axios").default;

var options = {
  method: 'GET',
  url: 'https://%7ByourGceProject%7D.appspot.com/airportName',
  params: {iataCode: 'SFO'},
  headers: {authorization: 'Bearer {accessToken}'}
};

axios.request(options).then(function (response) {
  console.log(response.data);
}).catch(function (error) {
  console.error(error);
});

Was this helpful?

/
#import <Foundation/Foundation.h>

NSDictionary *headers = @{ @"authorization": @"Bearer {accessToken}" };

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO"]
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:10.0];
[request setHTTPMethod:@"GET"];
[request setAllHTTPHeaderFields:headers];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                if (error) {
                                                    NSLog(@"%@", error);
                                                } else {
                                                    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                                                    NSLog(@"%@", httpResponse);
                                                }
                                            }];
[dataTask resume];

Was this helpful?

/
$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "https://%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => [
    "authorization: Bearer {accessToken}"
  ],
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

Was this helpful?

/
import http.client

conn = http.client.HTTPSConnection("")

headers = { 'authorization': "Bearer {accessToken}" }

conn.request("GET", "%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO", headers=headers)

res = conn.getresponse()
data = res.read()

print(data.decode("utf-8"))

Was this helpful?

/
require 'uri'
require 'net/http'
require 'openssl'

url = URI("https://%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

request = Net::HTTP::Get.new(url)
request["authorization"] = 'Bearer {accessToken}'

response = http.request(request)
puts response.read_body

Was this helpful?

/
import Foundation

let headers = ["authorization": "Bearer {accessToken}"]

let request = NSMutableURLRequest(url: NSURL(string: "https://%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()

Was this helpful?

/

これで作業完了です。