codekingpro/portable-devtools
114k
1import time2import logging3from authlib.jose import jwt, JoseError, JWTClaims4from ..rfc6749 import TokenMixin5from ..rfc6750 import BearerTokenValidator6 7logger = logging.getLogger(__name__)8 9 10class JWTBearerToken(TokenMixin, JWTClaims):11 def check_client(self, client):12 return self['client_id'] == client.get_client_id()13 14 def get_scope(self):15 return self.get('scope')16 17 def get_expires_in(self):18 return self['exp'] - self['iat']19 20 def is_expired(self):21 return self['exp'] < time.time()22 23 def is_revoked(self):24 return False25 26 27class JWTBearerTokenValidator(BearerTokenValidator):28 TOKEN_TYPE = 'bearer'29 token_cls = JWTBearerToken30 31 def __init__(self, public_key, issuer=None, realm=None, **extra_attributes):32 super().__init__(realm, **extra_attributes)33 self.public_key = public_key34 claims_options = {35 'exp': {'essential': True},36 'client_id': {'essential': True},37 'grant_type': {'essential': True},38 }39 if issuer:40 claims_options['iss'] = {'essential': True, 'value': issuer}41 self.claims_options = claims_options42 43 def authenticate_token(self, token_string):44 try:45 claims = jwt.decode(46 token_string, self.public_key,47 claims_options=self.claims_options,48 claims_cls=self.token_cls,49 )50 claims.validate()51 return claims52 except JoseError as error:53 logger.debug('Authenticate token failed. %r', error)54 return None55 