关于python:如何在Flask上使用Authlib 2.0获取身份验证代码/令牌?

How to get a authentication code / token using Authlib 2.0 on Flask?

我已多次阅读Authlib文档和示例示例,也曾阅读过有关Auth 2.0概念的文章,但我不知道该怎么做。我希望我的用户登录(使用用户名和密码),然后我的应用程序返回令牌。之后,用户可以使用专用资源@require_oauth('profile')

我的客户 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
*************************** 1. row ***************************
                 client_id: wmahDfsran1jk6CaH1knpi3n
             client_secret: mnr4j15pZurBPYHq4KW4LY8HC7pS4TwjzMlJAUGmo7Bpy5gP
                 issued_at: 1531271519
                expires_at: 0
              redirect_uri: http://127.0.0.1:5000/oauth/token
token_endpoint_auth_method: client_secret_basic
                grant_type: authorization_code password
             response_type: code
                     scope: profile
               client_name: client_test
                client_uri: http://127.0.0.1:5000/
                  logo_uri: NULL
                   contact: NULL
                   tos_uri: NULL
                policy_uri: NULL
                  jwks_uri: NULL
                 jwks_text: NULL
             i18n_metadata: NULL
               software_id: NULL
          software_version: NULL
                        id: 2
                   user_id: 1

我的POST请求(使用邮递员):

1
http://127.0.0.1:5000/oauth/authorize?response_type=code&client_id=wmahDfsran1jk6CaH1knpi3n

发出请求后的错误:

1
2
3
{
   "error":"invalid_grant"
}

授权:

1
2
3
4
5
6
7
8
9
10
@routes.route('/oauth/authorize', methods=['GET', 'POST'])
def authorize():  
    user = current_user()

    try:
        grant = authorization.validate_consent_request(end_user=user)
    except OAuth2Error as error:
        return error.error

    return authorization.create_authorization_response(grant_user=user)

代币:

1
2
3
@routes.route('/oauth/token', methods=['POST', 'GET'])
def issue_token():
    return authorization.create_token_response()

简介:

1
2
3
4
5
6
@routes.route('/resource/profile', methods=['GET', 'POST'])
@require_oauth('profile')
def profile():
    user = current_user()

    return jsonify(id=user.id, username=user.username, secret=user.secret, client_id=user.client_id)

令牌与Auth示例相同。

如果我尝试不带令牌/ autoriza ?? o访问/resource/profile

1
{"error":"missing_authorization","error_description":"Missing "Authorization" in headers."}

我该如何解决?

Obs:解决此问题后,如何获取Auth Token并将标头发送到/resource/profile

其他参考:使用OAuth 2.0代码授予流,OAuth 2.0:概述,invalid_grant尝试从Google获取oAuth令牌,授权对Azure Active Directory Web应用程序的访问
问,刷新访问令牌时出现" invalid_grant"错误的情况?
,授权码授予返回invalid_grant
...


I want my user to make login (Using username and password) and then my application to return a token

在这种情况下,您需要的是grant_type=password流,该流可以在https://docs.authlib.org/en/latest/flask/oauth2.html#resource-owner-password-credentials-grant中找到

在以下网址了解其工作原理:https://tools.ietf.org/html/rfc6749#section-4.3