我正在使用App Engine Standard和Python 2运行时和端点框架。在发出请求时,如果请求完成,应用程序只返回“成功”。我正在尝试实现身份验证,因此未经身份验证的用户无法完成请求。我做了以下事情:
issuers={'serviceAccount': endpoints.Issuer('[MYSERVICEACCOUNT]', 'https://www.googleapis.com/robot/v1/metadata/x509/[MYSERVICEACCOUNT]')},
audiences={'serviceAccount': ['[MYSERVICENAME]-dot-[MYPROJECT].appspot.com']}
user = endpoints.get_current_user()
if user is None:
raise endpoints.UnauthorizedException('You must authenticate first.')
要向我的应用程序发出授权请求,我已完成以下操作:
payload = json.dumps({
"iat": now,
"exp": now + 3600,
"iss": [MYSERVICEACCOUNT],
"sub": [MYSERVICEACCOUNT],
"aud": [MYSERVICENAME]-dot-[MYPROJECT].appspot.com
})
headers = {
'Authorization': 'Bearer {}'.format(signed_jwt),
'content-type': 'application/json'}
我收到401客户端错误:未经授权的网址错误。我错过了什么吗?
您的受众群体不匹配;在您的代码中,您需要[MYSERVICEACCOUNT]
的观众,但在生成JWT时,您的观众是[MYSERVICENAME]-dot-[MYPROJECT].appspot.com
。这些需要匹配。
有一些细节,可能值得检查:
aud
声明的值。这就是罗斯所指出的。email
字典中的payload
声明。scopes
装饰的@endpoints.method
字段。在与Google打开支持票后,结果显示Google的文档不正确。 main.py函数需要以下面的方式检查经过身份验证的用户:
providers=[{
'issuer': '[YOUR-SERVICE-ACCOUNT]',
'cert_uri': 'https://www.googleapis.com/service_accounts/v1/metadata/raw/[YOUR-SERVICE-ACCOUNT]',
}]
audiences = ['[YOUR-SERVICE-NAME]-dot-[YOUR-PROJECT-NAME].appspot.com']
user = endpoints.get_verified_jwt(providers, audiences, request=request)
if not user:
raise endpoints.UnauthorizedException
进行此更改后,尝试进行身份验证请求时出现以下错误:
从ProtoRPC方法实现遇到意外错误:AttributeError('unicode'对象没有属性'get')
这是由于我如何使用json.dumps()生成有效负载。我生成没有json.dumps()如下所示:
payload = {
"iat": now,
"exp": now + 3600,
"iss": [MYSERVICEACCOUNT],
"sub": [MYSERVICEACCOUNT],
"aud": [MYSERVICENAME]-dot-[MYPROJECT].appspot.com
}
这两个变化解决了我的问题。