Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
token.py94 linesDownload Raw Back to rfc7523
1import time2from authlib.common.encoding import to_native3from authlib.jose import jwt4 5 6class JWTBearerTokenGenerator:7    """A JSON Web Token formatted bearer token generator for jwt-bearer grant type.8    This token generator can be registered into authorization server::9 10        authorization_server.register_token_generator(11            'urn:ietf:params:oauth:grant-type:jwt-bearer',12            JWTBearerTokenGenerator(private_rsa_key),13        )14 15    In this way, we can generate the token into JWT format. And we don't have to16    save this token into database, since it will be short time valid. Consider to17    rewrite ``JWTBearerGrant.save_token``::18 19        class MyJWTBearerGrant(JWTBearerGrant):20            def save_token(self, token):21                pass22 23    :param secret_key: private RSA key in bytes, JWK or JWK Set.24    :param issuer: a string or URI of the issuer25    :param alg: ``alg`` to use in JWT26    """27    DEFAULT_EXPIRES_IN = 360028 29    def __init__(self, secret_key, issuer=None, alg='RS256'):30        self.secret_key = secret_key31        self.issuer = issuer32        self.alg = alg33 34    @staticmethod35    def get_allowed_scope(client, scope):36        if scope:37            scope = client.get_allowed_scope(scope)38        return scope39 40    @staticmethod41    def get_sub_value(user):42        """Return user's ID as ``sub`` value in token payload. For instance::43 44            @staticmethod45            def get_sub_value(user):46                return str(user.id)47        """48        return user.get_user_id()49 50    def get_token_data(self, grant_type, client, expires_in, user=None, scope=None):51        scope = self.get_allowed_scope(client, scope)52        issued_at = int(time.time())53        data = {54            'scope': scope,55            'grant_type': grant_type,56            'iat': issued_at,57            'exp': issued_at + expires_in,58            'client_id': client.get_client_id(),59        }60        if self.issuer:61            data['iss'] = self.issuer62        if user:63            data['sub'] = self.get_sub_value(user)64        return data65 66    def generate(self, grant_type, client, user=None, scope=None, expires_in=None):67        """Generate a bearer token for OAuth 2.0 authorization token endpoint.68 69        :param client: the client that making the request.70        :param grant_type: current requested grant_type.71        :param user: current authorized user.72        :param expires_in: if provided, use this value as expires_in.73        :param scope: current requested scope.74        :return: Token dict75        """76        if not expires_in:77            expires_in = self.DEFAULT_EXPIRES_IN78 79        token_data = self.get_token_data(grant_type, client, expires_in, user, scope)80        access_token = jwt.encode({'alg': self.alg}, token_data, key=self.secret_key, check=False)81        token = {82            'token_type': 'Bearer',83            'access_token': to_native(access_token),84            'expires_in': expires_in85        }86        if scope:87            token['scope'] = scope88        return token89 90    def __call__(self, grant_type, client, user=None, scope=None,91                 expires_in=None, include_refresh_token=True):92        # there is absolutely no refresh token in JWT format93        return self.generate(grant_type, client, user, scope, expires_in)94