这些消息是由于端点库尝试自动从Authorization
标头,以便它可以提供endpoints.get_current_user
(source https://code.google.com/p/googleappengine/source/browse/trunk/python/lib/endpoints-1.0/endpoints/users_id_token.py#95)。当Authorization
header 包含一个 Bearer 令牌,该令牌是有效的 Google OAuth2 访问令牌或 Android ID 令牌。
简单来说,这不是错误,只是无法自动地处理您的授权标头。没什么大不了的,因为你是通过智威汤逊使用你自己的。
对于 JWT,您仍然可以使用Authorization
标头并使用自己验证 JWTPyJWT
(要安装第三方软件包,请参阅here https://cloud.google.com/appengine/docs/python/tools/libraries27?hl=en#vendoring).
这是一个完整的示例:
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])
您可以使用自行生成的 jwt 令牌进行测试:
$ python -c "import jwt; print jwt.encode({'some': 'data'}, 'secret')"
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzb21lIjoiZGF0YSJ9.g1aG08iQyPPwCTJHCxRrkKoYmLiHbBNdarcBQkCPMG4
然后使用httpie https://github.com/jkbrzt/httpie提出请求:
$ http GET :8080/_ah/api/example/v1/auth Authorization:'Token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzb21lIjoiZGF0YSJ9.g1aG08iQyPPwCTJHCxRrkKoYmLiHbBNdarcBQkCPMG4'
如果您不喜欢看到有关无法每次验证令牌的端点日志,您可以使用自己的标头,例如X-Auth
.