如何向Google Cloud Endpoint进行身份验证的呼叫?

时间:2019-01-06 23:05:15

标签: authentication google-cloud-platform google-cloud-endpoints restful-authentication

我已经按照以下教程中的步骤设置了一个简单的标准环境Google App Engine项目,该项目使用Cloud Endpoints:

https://cloud.google.com/endpoints/docs/frameworks/python/get-started-frameworks-python

这很好用-我可以对echo端点进行curl调用并获得预期的结果。

但是,我无法成功调用经过身份验证的终结点。 我正在按照以下步骤操作:https://cloud.google.com/endpoints/docs/frameworks/python/javascript-client,尽管我可以成功登录,但是当我发送经过身份验证的示例请求时,我收到401未经授权的HTTP响应。

从服务器上的日志中,我看到:

Client ID is not allowed: <my client id>.apps.googleusercontent.com (/base/data/home/apps/m~bfg-data-analytics/20190106t144214.415219868228932029/lib/endpoints/users_id_token.py:508)

到目前为止,我已经检查了:

  • 该Web应用正在使用正确版本的云端点配置。
  • 端点配置(x-google-audiences)中的客户端ID与 javascript Web应用程序正在发布的客户端ID。

关于如何解决此问题的任何想法?

1 个答案:

答案 0 :(得分:0)

Using the example code to set up the end point in: https://cloud.google.com/endpoints/docs/frameworks/python/create_api and https://cloud.google.com/endpoints/docs/frameworks/python/service-account-authentication

And modifying the python code for generating a token from : https://github.com/GoogleCloudPlatform/python-docs-samples/tree/master/endpoints/getting-started/clients/service_to_service_google_id_token

I've got it working.

Here's the server endpoint code:

import endpoints
from endpoints import message_types
from endpoints import messages
from endpoints import remote

class EchoRequest(messages.Message):
    message = messages.StringField(1)

class EchoResponse(messages.Message):
    """A proto Message that contains a simple string field."""
    message = messages.StringField(1)


ECHO_RESOURCE = endpoints.ResourceContainer(
    EchoRequest,
    n=messages.IntegerField(2, default=1))

@endpoints.api(
    name='echo',
    version='v1',
    issuers={'serviceAccount': endpoints.Issuer(
    'MY-PROJECT@appspot.gserviceaccount.com',
    'https://www.googleapis.com/robot/v1/metadata/x509/MY-PROJECT@appspot.gserviceaccount.com')},
    audiences={'serviceAccount': ['MY-PROJECT@appspot.gserviceaccount.com']})

class EchoApi(remote.Service):
    # Authenticated POST API
    # curl -H "Authorization: Bearer $token --request POST --header "Content-Type: applicationjson" --data '{"message":"echo"}' https://MY-PROJECT@appspot.com/_ah/api/echo/v1/echo?n=5
    @endpoints.method(
        # This method takes a ResourceContainer defined above.
        ECHO_RESOURCE,
        # This method returns an Echo message.
        EchoResponse,
        path='echo',
        http_method='POST',
        name='echo')
    def echo(self, request):
        print "getting current user"
        user = endpoints.get_current_user()
        print user
        # if user == none return 401 unauthorized
        if not user:
            raise endpoints.UnauthorizedException

        # Create an output message including the user's email
        output_message = ' '.join([request.message] * request.n) + ' ' + user.email()
        return EchoResponse(message=output_message)

api = endpoints.api_server([EchoApi])

And the code to generate a valid token

    import base64
    import json
    import time
    import google

    import google.auth
    from google.auth import jwt

    def generate_token(audience, json_keyfile, client_id, service_account_email):
        signer = google.auth.crypt.RSASigner.from_service_account_file(json_keyfile)

        now = int(time.time())
        expires = now + 3600  # One hour in seconds

        payload = {
            'iat': now,
            'exp': expires,
            'aud' : audience,
            'iss': service_account_email,
            'sub': client_id,
            'email' : service_account_email
        }

        jwt = google.auth.jwt.encode(signer, payload)

        return jwt

token = generate_token(
    audience="MY-PROJECT@appspot.gserviceaccount.com",              # must match x-google-audiences
    json_keyfile="./key-file-for-service-account.json",
    client_id="xxxxxxxxxxxxxxxxxxxxx",                              # client_id from key file
    service_account_email="MY-PROJECT@appspot.gserviceaccount.com")

print token

Make an authenticated call with curl

export token=`python main.py` 
curl -H "Authorization: Bearer $token" --request POST --header "Content-Type: application/json" --data '{"message":"secure"}' https://MY-PROJECT.appspot.com/_ah/api/echo/v1/echo?n=5