首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Authlib 0.11的JWT令牌生成器

使用Authlib 0.11的JWT令牌生成器
EN

Stack Overflow用户
提问于 2019-06-22 13:11:12
回答 1查看 1.6K关注 0票数 2

首先:非常感谢Authlib创建者/其他开源创建者和支持者。

我希望使用Authlib 0.11将oauth令牌作为JWT返回。我试图按照Authlib网站中提供的文档创建一个带有Authlib 0.11 https://docs.authlib.org/en/latest/flask/2/authorization-server.html#token的JWT令牌生成器。

由于我是本主题的新手用户,我仍然无法找到将JWT令牌生成器方法传递给config:OAUTH2_ACCESS_TOKEN_GENERATOR的正确方法。

任何帮助都是非常感谢的。

下面是我的虚拟jwt令牌生成器:

代码语言:javascript
复制
from authlib.jose import jwt
def gen_access_token(client, grant_type, user, scope):
    log.debug('Not used yet in the JWT:: {} \n{} \n{} \n{}'.format( client, grant_type, user, scope))
    header = {'alg': 'RS256'}
    payload = {
        'iss': 'http://127.0.0.1:5000/oauth/token',
        'sub': 'test client',
        'aud': 'profile'
    }
    try:
        key = open('wf-app-server.key', 'r').read()
        s = jwt.encode(header, payload, key)
        claims = jwt.decode(s, open('wf-app-pub.pem', 'r').read())
    except Exception as e:
        log.debug('JWT exception', e)
    log.debug("jwt encoded:{}\n decoded :{} \n header:{}".format(
        s, claims, claims.header))
    return s

OAUTH2_REFRESH_TOKEN_GENERATOR = True
OAUTH2_TOKEN_EXPIRES_IN = {
    'authorization_code': 874000,
    'implicit': 3600,
    'password': 600000,
    'client_credentials': 600000
    }

OAUTH2_ACCESS_TOKEN_GENERATOR = gen_access_token('bCsNV2Lo8hxD593Km84lWM5d', 'client_credentials', 'admin', 'profile') 

--输出显示我的JWT令牌生成器工作,返回的值可以正确解码--

代码语言:javascript
复制
2019-06-22 13:37:38,024 DEBUG gen_access_token (7) Not used yet in the JWT:: bCsNV2Lo8hxD593Km84lWM5d  client_credentials  admin  profile

2019-06-22 13:37:38,052 DEBUG gen_access_token (21) jwt encoded:b'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwOi8vMTI3LjAuMC4xOjUwMDAvb2F1dGgvdG9rZW4iLCJzdWIiOiJ0ZXN0IGNsaWVudCIsImF1ZCI6InByb2ZpbGUifQ.BU5dSbPAFzoDDo4vathd6jlQVmDHaygEUh4GCwknCdbf4AVig3SgOW8JbITuPCKTf7qnxE8iJCWUOAd_wDCZwWKXdpisG6EGGmNpwZLAsDqL1CLgqTsRuGrc2kUfyMOHXfGXGkqsNROuPFV0-XYgxCQOz4LolNcB3Knvu1ApRcZyej8nAFXKxccDkLYyhldjRJwRehRZ4tMjDlbP4ghmEUFBF1Msx5Yzot26IK3ps4dfLnYVJr2dKUIPK75BzYR5kgUm3nkJRe4F0898j8tIMZwvKa2lKSypORDQXUxC3i8-x7A2vsVk7Jw3qcbZBarqstUEWITCZSVPYoHoF5l8iw'

decoded :{'iss': 'http://127.0.0.1:5000/oauth/token', 'sub': 'test  client', 'aud': 'profile'}   header:{'alg': 'RS256', 'typ': 'JWT'}

首先,为了测试我的oauth令牌请求凭据是否正确,我尝试使用正确的client_credentials和来自Authlib的默认token_generator请求oauth令牌。这样我就得到了默认的oauth令牌。

其次,我用令牌生成器更新了配置,然后当我请求具有相同客户端凭据的oauth令牌时,我会得到以下错误:

代码语言:javascript
复制
2019-06-22 13:40:56,700 DEBUG authenticate_client_secret_basic (65)
Authenticate bCsNV2Lo8hxD593Km84lWM5d via "client_secret_basic"
success

I created this custom debug line below to understand what the default access_token_generator() takes as input parameters. It is exactly take the same types - my input parameter types also match!

2019-06-22 13:40:56,701 DEBUG validate_token_request (67)
Validate token request of <OAuth2Client 2> client: <OAuth2Client 2>
type:<class 'website.models.OAuth2Client'> grant_type:
client_credentials type:<class 'str'> user: None type:<class
'NoneType'> scope: rs1secret type:<class 'str'> 

2019-06-22 13:40:56,708 INFO _log (122) 127.0.0.1 - - [22/Jun/2019 13:40:56] "POST /oauth/token HTTP/1.1" 500 - Traceback (most recent call last):  File  "/home/pksec/.local/share/virtualenvs/oAuthProvider-n_KOMqPA/lib/python3.7/site-packages/flask/app.py",
  line 2328, in __call__
return self.wsgi_app(environ, start_response)   File "/home/pksec/.local/share/virtualenvs/oAuthProvider-n_KOMqPA/lib/python3.7/site-packages/flask/app.py",
  line 2314, in wsgi_app
     response = self.handle_exception(e)   File "/home/pksec/.local/share/virtualenvs/oAuthProvider-n_KOMqPA/lib/python3.7/site-packages/flask/app.py",
 line 1760, in handle_exception
     reraise(exc_type, exc_value, tb)   File "/home/pksec/.local/share/virtualenvs/oAuthProvider-n_KOMqPA/lib/python3.7/site-packages/flask/_compat.py",
 line 36, in reraise
     raise value   File "/home/pksec/.local/share/virtualenvs/oAuthProvider-n_KOMqPA/lib/python3.7/site-packages/flask/app.py",
 line 2311, in wsgi_app
     response = self.full_dispatch_request()   File "/home/pksec/.local/share/virtualenvs/oAuthProvider-n_KOMqPA/lib/python3.7/site-packages/flask/app.py",
 line 1834, in full_dispatch_request
     rv = self.handle_user_exception(e)   File "/home/pksec/.local/share/virtualenvs/oAuthProvider-n_KOMqPA/lib/python3.7/site-packages/flask/app.py",
 line 1737, in handle_user_exception
     reraise(exc_type, exc_value, tb)   File "/home/pksec/.local/share/virtualenvs/oAuthProvider-n_KOMqPA/lib/python3.7/site-packages/flask/_compat.py",
 line 36, in reraise
     raise value   File "/home/pksec/.local/share/virtualenvs/oAuthProvider-n_KOMqPA/lib/python3.7/site-packages/flask/app.py",
 line 1832, in full_dispatch_request
     rv = self.dispatch_request()   File "/home/pksec/.local/share/virtualenvs/oAuthProvider-n_KOMqPA/lib/python3.7/site-packages/flask/app.py",
 line 1818, in dispatch_request
     return self.view_functions[rule.endpoint](**req.view_args)   File "/home/pksec/xx/oAuthProvider/website/routes.py",
 line 193, in issue_token
     return authorization.create_token_response()   File "/virtualenvs/oAuthProvider-n_KOMqPA/lib/python3.7/site-packages/authlib/oauth2/rfc6749/authorization_server.py",
 line 186, in create_token_response
     args = grant.create_token_response()   File "/home/pksec/.local/share/virtualenvs/oAuthProvider-n_KOMqPA/lib/python3.7/site-packages/authlib/oauth2/rfc6749/grants/client_credentials.py",
 line 104, in create_token_response
     include_refresh_token=False,   File "/home/pksec/.local/share/virtualenvs/oAuthProvider-n_KOMqPA/lib/python3.7/site-packages/authlib/oauth2/rfc6749/grants/base.py",
 line 58, in generate_token
     include_refresh_token=include_refresh_token,   File "/home/pksec/.local/share/virtualenvs/oAuthProvider-n_KOMqPA/lib/python3.7/site-packages/authlib/oauth2/rfc6750/wrappers.py",
 line 91, in __call__
     access_token = self.access_token_generator(client, grant_type, user, scope) TypeError: 'NoneType' object is not callable

我知道,当我将gen_acc_token()方法传递给配置时,我做了一些错误的事情--但我无法准确地找出问题所在。

传递示例gen_JWT_access_token()的一个小代码片段将非常好。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-23 10:32:59

我终于找到了将JWT令牌生成器方法传递给config:OAUTH2_ACCESS_TOKEN_GENERATOR的正确方法。

下面是我的虚拟jwt令牌生成器:

代码语言:javascript
复制
from authlib.jose import jwt
def gen_access_token(client, grant_type, user, scope):
    log.debug('Not used yet in the JWT:: {} \n{} \n{} \n{}'.format( client, grant_type, user, scope))
    header = {'alg': 'RS256'}
    payload = {
        'iss': 'http://127.0.0.1:5000/oauth/token',
        'sub': 'test client',
        'aud': 'profile'
    }
    try:
        key = open('wf-app-server.key', 'r').read()
        s = jwt.encode(header, payload, key)
        claims = jwt.decode(s, open('wf-app-pub.pem', 'r').read())
    except Exception as e:
        log.debug('JWT exception', e)
    log.debug("jwt encoded:{}\n decoded :{} \n header:{}".format(
        s, claims, claims.header))
    return s

OAUTH2_REFRESH_TOKEN_GENERATOR = True
OAUTH2_TOKEN_EXPIRES_IN = {
    'authorization_code': 874000,
    'implicit': 3600,
    'password': 600000,
    'client_credentials': 600000
    }
OAUTH2_ACCESS_TOKEN_GENERATOR = gen_access_token

不要传递函数参数:Python NoneType object is not callable (beginner)

这是初学者的错误!跟着你的错误输出,你会找到解决方案的!

这就是不应该传递生成器函数的方式:

代码语言:javascript
复制
OAUTH2_ACCESS_TOKEN_GENERATOR = gen_access_token('bCsNV2Lo8hxD593Km84lWM5d', 'client_credentials', 'admin', 'profile')
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56715779

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档