我在我的烧瓶应用程序中实现了 OAuth2 客户端凭据授予。
楷模
class User(UserMixin, db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
confirmed = db.Column(db.Boolean, default=False)
first_name = db.Column(db.String(64), index=True)
last_name = db.Column(db.String(64), index=True)
email = db.Column(db.String(64), unique=True, index=True)
password_hash = db.Column(db.String(128))
role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
from authlib.flask.oauth2.sqla import OAuth2ClientMixin
class Client(db.Model, OAuth2ClientMixin):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(
db.Integer, db.ForeignKey('users.id', ondelete='CASCADE')
)
user = db.relationship('User')
app_id = db.Column(db.ForeignKey('app.application_id'))
app = db.relationship('App')
from authlib.flask.oauth2.sqla import OAuth2TokenMixin
class Token(db.Model, OAuth2TokenMixin):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(
db.Integer, db.ForeignKey('users.id', ondelete='CASCADE')
)
user = db.relationship('User')
初始化.py
from authlib.flask.oauth2 import AuthorizationServer
server = AuthorizationServer()
def create_app(config_name):
app = Flask(__name__)
...
from app.api.auth.views import query_client, ClientCredentialsGrant
server.init_app(app, query_client=query_client)
server.register_grant_endpoint(ClientCredentialsGrant)
应用程序/api/auth/views.py
def query_client(client_id):
return Client.query.filter_by(client_id=client_id).first()
from authlib.specs.rfc6749.grants import (
ClientCredentialsGrant as _ClientCredentialsGrant
)
class ClientCredentialsGrant(_ClientCredentialsGrant):
def create_access_token(self, token, client):
current_app.logger.info("RadhaKrishna")
item = Token(
client_id=client.client_id,
user_id=client.user_id,
**token
)
db.session.add(item)
db.session.commit()
@auth.route('/oauth/token', methods=['POST'])
@csrf.exempt
def issue_token():
return server.create_token_response()
但是,我无法使身份验证正常工作。我使用正确的客户端凭据、范围和 grant_type 向令牌端点发出请求,但出现 invalid_client 错误。