客户端无权使用此方法请求授权码

时间:2018-09-21 20:02:44

标签: python flask authlib

我需要在GET请求上Authlib生成一个授权令牌。用户不需要确认对资源的访问,因为它是封闭的网络,只有受信任的服务(我们的服务)才能发送请求。
使用OAuth 2.0提供程序的this sample,我写了下一个:
路线中:

@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。它说客户已被授权,但我想授权它,当然,它是未授权的。怎么了?
P.S。 my repository

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

1 个答案:

答案 0 :(得分:0)

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