0

我需要在 GET 请求 Authlib 上生成一个授权令牌。用户不需要确认对资源的访问,因为它是封闭的网络,只有受信任的服务(我们的服务)可以发送请求。
使用此OAuth 2.0 Provider示例
,我编写了下一个: 在路由中:

@bp.route("/oauth/authorize", methods=['GET'])
@login_required
def authorize():
    user = current_user()
    return server.create_authorization_response(grant_user=user)

我的oauth模块:

server = AuthorizationServer()
require_oauth = ResourceProtector()


class AuthorizationCodeGrant(grants.AuthorizationCodeGrant):
    def create_authorization_code(self, client, grant_user, request):
        # you can use other method to generate this code
        code = generate_token(48)
        item = AuthorizationCode(
            code=code,
            client_id=client.client_id,
            redirect_uri=request.redirect_uri,
            scope=request.scope,
            user_id=grant_user.get_user_id(),
        )
        db.session.add(item)
        db.session.commit()
        return code

    def parse_authorization_code(self, code, client):
        item = AuthorizationCode.query.filter_by(code=code, client_id=client.client_id)\
            .first()
        if item and not item.is_expired():
            return item

    def delete_authorization_code(self, authorization_code):
        db.session.delete(authorization_code)
        db.session.commit()

    def authenticate_user(self, authorization_code):
        return User.query.get(authorization_code.user_id)


def current_user():
    if 'id' in session:
        uid = session['id']
        return User.query.get(uid)
    return None


def query_client(client_id):
    return Client.query.filter_by(client_id=client_id).first()


def save_token(token, request):
    if request.user:
        user_id = request.user.get_user_id()
    else:
        # client_credentials grant_type
        user_id = request.client.user_id
    item = Token(
        client_id=request.client.client_id,
        user_id=user_id,
        **token
    )
    db.session.add(item)
    db.session.commit()


def init_oauth2(app):
    server.init_app(app, query_client=query_client, save_token=save_token)
    # register it to grant endpoint
    server.register_grant(AuthorizationCodeGrant)

但是当我尝试发送请求时:

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

服务器返回错误:

{
    "error": "unauthorized_client", 
    "error_description": "The client is not authorized to request an authorization code using this method"
}

我启用了不安全的传输模式,并且该客户端已在数据库中注册。我client_id从数据库中取出了它select client_id from clients。它说客户端是授权的,但我想授权它,当然,它是未经授权的。怎么了?
PS 我的仓库

添加:
我需要response_type为客户指定。

4

1 回答 1

1

这意味着您的客户端不支持代码响应类型。客户端上有一个 check_response_type 方法,确保它会返回 True。

于 2018-09-22T02:03:35.007 回答