Google Cloud Endpoints和JWT [英] Google Cloud Endpoints and JWT

查看:112
本文介绍了Google Cloud Endpoints和JWT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于Google Cloud Endpoints的API,我想使用JWT(Json Web Tokens)进行授权。我可以为包含令牌的每个请求设置授权标头,并且它可以正常工作。我知道端点使用Oauth2的这个头文件,这是我的问题。对自定义标记使用授权标头是否正确? GAE日志:

  D 12:38:44.375检查id_token。 
D 12:38:44.376 id_token验证失败:意外的加密算法:u'HS256'
D 12:38:44.376检查oauth标记。
D 12:38:44.384 Oauth框架用户与oauth令牌用户不匹配。

它看起来像GAE试图将这个标记作为oauth标记读取,它不好,对吗?也许我应该在URL中发送我的令牌?类似于app-id.appspot.com/_ah/api/my_app/v1/users/get?jwt=TOKEN。也许我不应该使用JWT和Google Cloud Endpoints?

用户从 Authorization 标题,以便它可以提供 endpoints.get_current_user )。当 Authorization 标头包含一个Bearer标记,它是有效的Google OAuth2访问标记或Android ID标记时,它可以自动执行此操作。



简单地说,这不是一个错误,它只是不能自动处理您的授权标头。对于JWT,您仍可以使用 Authorization ,因为您通过JWT与自己的用户进行了交易。 >标题并使用 PyJWT 自己验证JWT(要安装第三方软件包,请参阅)。

这是一个完整的示例:

导入日志

导入endpoints $ b $ from protorpc导入消息
from protorpc import message_types
from protorpc import remote
$ b $ import jwt

$ b class TestMessage(messages.Message):
message = messages.StringField(1)


@ endpoints.api(name ='example',version ='v1')
class ExampleApi(remote.Service):
@ endpoints.method(message_types .VoidMessage,TestMessage,http_method ='GET')
def auth(self,unused_request):

#获取HTTP授权n头。
auth_header = self.request_state.headers.get('authorization')
如果不是auth_header:
raise ends.UnauthorizedException(No authorization header。)

#获取编码的jwt令牌。
auth_token = auth_header.split('').pop()

#解码并验证令牌
尝试:
payload = jwt.decode(auth_token,'秘密')
#在这里做你自己的支票。
logging.info(有效负载)
,除了jwt.InvalidTokenError:
引发endpoints.UnauthorizedException(令牌验证失败。)

返回TestMessage(message ='OK ')


app = endpoints.api_server([ExampleApi])



  $ python -cimport jwt; print jwt。您可以使用自生jwt令牌来测试它:

编码({'some':'data'},'secret')
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzb21lIjoiZGF0YSJ9.g1aG08iQyPPwCTJHCxRrkKoYmLiHbBNdarcBQkCPMG4

然后使用 httpie 发出请求:

  $ http GET:8080 / _ah / api / example / v1 / auth授权:'Token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzb21lIjoiZGF0YSJ9.g1aG08iQyPPwCTJHCxRrkKoYmLiHbBNdarcBQkCPMG4'

如果您不喜欢看到关于无法使用val的端点日志每次都可以使用自己的标头,比如 X-Auth


I have an API based on Google Cloud Endpoints and I want to use JWT (Json Web Tokens) for authorization. I can set Authorization header for every request which contains token and it works correctly. I know that Endpoints uses this header for Oauth2 and here is my question. Is it correct to use Authorization header for custom token? GAE logs:

D 12:38:44.375 Checking for id_token.
D 12:38:44.376 id_token verification failed: Unexpected encryption algorithm: u'HS256'
D 12:38:44.376 Checking for oauth token.
D 12:38:44.384 Oauth framework user didn't match oauth token user.

It looks like GAE tries to read this token as oauth token and it is not good, right? Maybe I should send my token in URL? Something like app-id.appspot.com/_ah/api/my_app/v1/users/get?jwt=TOKEN. Maybe I shouldn't use JWT with Google Cloud Endpoints?

解决方案

These messages are due to the endpoints library attempting to automatically determine the user from the Authorization header so that it can provide endpoints.get_current_user (source). It can do this automatically when the Authorization header contains a Bearer token that is a valid Google OAuth2 access token or an Android ID token.

Simply put, this is not an error, it's just not able to automatically process your Authorization header. No big deal since you're going with your own via JWT.

For JWTs, you can still use the Authorization header and validate the JWT yourself using PyJWT (to install third-party packages, see here).

Here's a complete sample:

import logging

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

import jwt


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


@endpoints.api(name='example', version='v1')
class ExampleApi(remote.Service):
    @endpoints.method(message_types.VoidMessage, TestMessage, http_method='GET')
    def auth(self, unused_request):

        # Get the HTTP Authorization header.
        auth_header = self.request_state.headers.get('authorization')
        if not auth_header:
            raise endpoints.UnauthorizedException("No authorization header.")

        # Get the encoded jwt token.
        auth_token = auth_header.split(' ').pop()

        # Decode and verify the token
        try:
            payload = jwt.decode(auth_token, 'secret')
            # Do your own check here.
            logging.info(payload)
        except jwt.InvalidTokenError:
            raise endpoints.UnauthorizedException("Token validation failed.")

        return TestMessage(message='OK')


app = endpoints.api_server([ExampleApi])

You can test this with a self-generated jwt token:

$ python -c "import jwt; print jwt.encode({'some': 'data'}, 'secret')"
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzb21lIjoiZGF0YSJ9.g1aG08iQyPPwCTJHCxRrkKoYmLiHbBNdarcBQkCPMG4

Then use httpie to make a request:

$ http GET :8080/_ah/api/example/v1/auth Authorization:'Token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzb21lIjoiZGF0YSJ9.g1aG08iQyPPwCTJHCxRrkKoYmLiHbBNdarcBQkCPMG4'

If you don't like seeing the endpoints logs about not being able to validate the token every time, you can use your own header, like X-Auth.

这篇关于Google Cloud Endpoints和JWT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆