def verify_token(self, encoded_token: str) -> dict: try: claims = jwt.decode( encoded_token, self.rsa_pubkey if self.auth_type.startswith("RS") else self.secret_key, issuer=self.issuer, algorithms=[self.auth_type], options={ "require": ["exp", "iss", "sub", "iat"], "verify_iat": True, "verify_exp": True, "verify_iss": True, "verify_signature": True, }, ) if "type" not in claims or claims["type"] not in {"auth", "refresh"}: raise jwt.InvalidTokenError() if ("scope" if claims["type"] == "auth" else "rid") in claims: return {"valid": True, **claims} else: raise jwt.InvalidTokenError() except jwt.InvalidTokenError as e: if isinstance(e, jwt.ExpiredSignatureError): error = "expired" else: error = "invalid" return {"valid": False, "error": error}
def get_user_from_payload(payload: Dict[str, Any]) -> Optional[User]: user = User.objects.filter(email=payload["email"], is_active=True).first() user_jwt_token = payload.get("token") if not user_jwt_token or not user: raise jwt.InvalidTokenError( "Invalid token. Create new one by using tokenCreate mutation.") if user.jwt_token_key != user_jwt_token: raise jwt.InvalidTokenError( "Invalid token. Create new one by using tokenCreate mutation.") return user
def refresh_token(token): """ Refresh a user's token if the token and user are valid. """ try: user = JWT.get_user_from_jwt(token) if user is not None: return JWT.get_user_token(user) else: raise jwt.InvalidTokenError('The provided token was invalid') except: raise jwt.InvalidTokenError('The provided token was invalid')
def identify(privilege): """ 用户鉴权 :return: list """ payload = __parse_jwt() user = user_db.get_user_by_id(payload['data']['id']) if user is None: raise jwt.InvalidTokenError('用户未找到') if user['login_time'] != payload['data']['login_time']: raise jwt.InvalidTokenError('权限验证失败') if privilege and ('type' not in user or privilege.value != user['type']): raise jwt.InvalidTokenError('权限验证失败')
def __parse_jwt(): auth_header = request.headers.get('Authorization') if not auth_header: raise Exception('没有证书') auth_tokens = auth_header.split(" ") if not auth_tokens or auth_tokens[0] != 'JWT' or len(auth_tokens) != 2: raise jwt.InvalidTokenError('jwt token不能被正确的解析') else: auth_token = auth_tokens[1] payload = __decode_auth_token(auth_token) if isinstance(payload, str): raise jwt.InvalidTokenError('jwt token 不能被正确的解析') return payload
def decode_token(token): try: return token except jwt.ExpiredSignatureError: raise jwt.ExpiredSignatureError() except jwt.InvalidTokenError: raise jwt.InvalidTokenError()
def decode_auth_token(auth_token, client): payload = jwt.decode(auth_token, SECRET_KEY) is_blacklisted_token = check_blacklist_token(auth_token, client) if is_blacklisted_token: raise jwt.InvalidTokenError('Please re-login to access the page') else: return payload['sub']
def authenticate(self, request): # 认证通过,返回user,auth # 认证失败,返回None auth = request.META.get('HTTP_AUTHORIZATION') # 前端用header中AUTHORIZATION携带token if auth is not None: token = auth.replace('JWT ','') #取出token else: token = None try: payload = jwt_decode_handler(token) #解析token print(payload) user = self.authenticate_credentials(payload) if user.is_staff == False: isAuth = Authentication(request.path,request.method) if isAuth==False: raise jwt.InvalidTokenError('没有权限') # 出现jwt解析异常,直接抛出异常,代表非法用户,也可以返回None,作为游客处理 except jwt.ExpiredSignature: raise AuthenticationFailed('token已过期') except jwt.InvalidTokenError: raise PermissionDenied('没有权限') except: raise AuthenticationFailed('token非法') return (user, auth)
def _decode_and_verify_token(token, jwt_issuer): options = { 'require': ["exp", "iat"], 'verify_exp': api_settings.JWT_VERIFY_EXPIRATION, 'verify_aud': settings.JWT_AUTH.get('JWT_VERIFY_AUDIENCE', True), 'verify_iss': False, # TODO (ARCH-204): manually verify until issuer is configured correctly. 'verify_signature': False, # Verified with JWS already } decoded_token = jwt.decode( token, jwt_issuer['SECRET_KEY'], options=options, leeway=api_settings.JWT_LEEWAY, audience=jwt_issuer['AUDIENCE'], issuer=jwt_issuer['ISSUER'], algorithms=[api_settings.JWT_ALGORITHM], ) # TODO (ARCH-204): verify issuer manually until it is properly configured. token_issuer = decoded_token.get('iss') issuer_matched = any(issuer['ISSUER'] == token_issuer for issuer in get_jwt_issuers()) if not issuer_matched: logger.info('Token decode failed due to mismatched issuer [%s]', token_issuer) raise jwt.InvalidTokenError('%s is not a valid issuer.' % token_issuer) return decoded_token
def decode_jwt(self, token: bytes): """Returns a decoded JWT's payload""" key = os.getenv("JWT_SECRET") try: decoded = jwt.decode( token, key, algorithms="HS256", issuer=AuthSettings.JWT_ISSUER, options={"require": ["exp", "iss", "email"]}, ) except jwt.ExpiredSignatureError: self._logger.log( LogEntry(LogLevel.INFO, __name__, "JWT Token expired for user.")) raise jwt.ExpiredSignatureError("Expired token.") except jwt.InvalidIssuerError: self._logger.log( LogEntry(LogLevel.ERROR, __name__, "Attempted to decode token with invalid issuer.")) raise jwt.InvalidIssuerError("Invalid JWT Issuer.") except jwt.InvalidTokenError: self._logger.log( LogEntry(LogLevel.ERROR, __name__, "JWT decoding error when trying to decode token.")) raise jwt.InvalidTokenError("Invalid token.") return decoded
def decode_token(): """Decode JWT token entered by the user.""" token = request.headers.get('Authorization') if token is None: return {} if token.startswith('Bearer '): _, token = token.split(' ', 1) pub_key = fetch_public_key(current_app) audiences = get_audiences() decoded_token = None for aud in audiences: try: decoded_token = jwt.decode(token, pub_key, audience=aud) except jwt.InvalidTokenError: decoded_token = None current_app.logger.error( 'Auth Token could not be decoded for audience {}'.format(aud)) if decoded_token is not None: break if decoded_token is None: raise jwt.InvalidTokenError('Auth token audience cannot be verified.') return decoded_token
def decode_token(token): """Decode the authorization token read from the request header.""" if token is None: return {} if token.startswith('Bearer '): _, token = token.split(' ', 1) pub_key = fetch_public_key(current_app) audiences = get_audiences() decoded_token = None for aud in audiences: try: decoded_token = jwt.decode(token, pub_key, algorithms=['RS256'], audience=aud) except jwt.InvalidTokenError: current_app.logger.error( 'Auth Token could not be decoded for audience {}'.format(aud)) decoded_token = None if decoded_token is not None: break if decoded_token is None: raise jwt.InvalidTokenError('Auth token audience cannot be verified.') return decoded_token
def decode_token(): """Decode the authorization token read from the request header.""" token = request.headers.get('Authorization') if token is None: return {} if token.startswith('Bearer '): _, token = token.split(' ', 1) pub_key = fetch_public_key(current_app) audiences = configuration.BAYESIAN_JWT_AUDIENCE.split(',') decoded_token = None for aud in audiences: try: decoded_token = jwt.decode(token.encode('ascii'), pub_key, algorithm='RS256', audience=aud) except jwt.InvalidTokenError: current_app.logger.error( 'Auth Token could not be decoded for audience {}'.format(aud)) decoded_token = None if decoded_token is not None: break if decoded_token is None: raise jwt.InvalidTokenError('Auth token audience cannot be verified.') return decoded_token
def decode_verify_jwt(token_encoded, token_uses): token_header = jwt.get_unverified_header(token_encoded) if current_app.logger.isEnabledFor(logging.DEBUG): # logger level checking is needed here because we don't want to invoke # jwt.decode(..., verify=False) when debug level is disabled current_app.logger.debug('JWT HEADER: %s | JWT PAYLOAD: %s', token_header, jwt.decode(token_encoded, verify=False)) jwk = current_app.config['COGNITO_JWK_DICT'][token_header['kid']] public_key = current_app.config['PYJWT_SIGN_ALG_CLASS'].from_jwk( json.dumps(jwk)) token_decoded = jwt.decode( token_encoded, public_key, verify=True, algorithms=current_app.config['JWT_SIGN_ALG_NAME'], # audience=current_app.config['COGNITO_APP_CLIENT_ID'], # (not present in access token generated by cognito) issuer=current_app.config['COGNITO_USER_POOL_URL']) if token_decoded['token_use'] not in token_uses: raise jwt.InvalidTokenError('Invalid token_use') # https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-verifying-a-jwt.html return token_decoded
def get_user_from_access_token(token: str) -> Optional[User]: payload = jwt_decode(token) jwt_type = payload.get("type") if jwt_type != JWT_ACCESS_TYPE: raise jwt.InvalidTokenError( "Invalid token. Create new one by using tokenCreate mutation.") return get_user_from_payload(payload)
def decode_token(): token = request.headers.get('Authorization') if token is None: return {} if token.startswith('Bearer '): _, token = token.split(' ', 1) pub_key = fetch_public_key(current_app) audiences = current_app.config.get('BAYESIAN_JWT_AUDIENCE').split(',') for aud in audiences: try: decoded_token = jwt.decode(token, pub_key, audience=aud) except jwt.InvalidTokenError: current_app.logger.error( 'Auth Token could not be decoded for audience {}'.format(aud)) decoded_token = None if decoded_token is not None: break if decoded_token is None: raise jwt.InvalidTokenError('Auth token audience cannot be verified.') return decoded_token
def get_jwt_token_from_request(request): auth_header = request.META.get('HTTP_AUTHORIZATION', '') auth_header_prefix = CONNECT_ARGS.auth_header_prefix if CONNECT_ARGS.verify: if not auth_header: raise jwt.InvalidTokenError( 'The Authorization header must not be empty.') if not auth_header.startswith(auth_header_prefix): raise jwt.InvalidTokenError( 'The Authorization header must start with "{}".'.format( auth_header_prefix)) token = auth_header[len(auth_header_prefix) + 1:] return token
def authenticate(self, req, *args, **kwargs): try: payload = super().authenticate(req, *args, **kwargs) except HTTPMissingHeader: try: token = req.params['api-key'] except KeyError: raise jwt.InvalidTokenError( "Missing 'api-key' query parameter") payload = self.decode(token) if self.verify_function: problem = self.verify_function(payload) if problem is not None: raise jwt.InvalidTokenError( f"Problematic JWT token '{problem}'") return payload
def __verify_payload(payload: Dict): user = get_user_by_payload(payload) jti = "" try: jti = payload["jti"] except: raise jwt.MissingRequiredClaimError("jti") if (not user.jtis.filter(value=jti).exists()): raise jwt.InvalidTokenError("Token expired by user-logout request")
def _verify_jwt_signature(token, jwt_issuer): key_set = _get_signing_jwk_key_set(jwt_issuer) try: _ = JWS().verify_compact(token, key_set) except Exception as token_error: logger.exception('Token verification failed.') exc_info = sys.exc_info() raise jwt.InvalidTokenError(exc_info[2]) from token_error
def get_token(self, req, *args, **kwargs): token = req.auth if not token: raise jwt.InvalidTokenError( f"Missing authorization '{self.http_header_prefix}' header with JWT data" ) # Ignore the header prefix, eg: Authorization: Bearer <token_data> if not token.startswith(f'{self.http_header_prefix} '): raise jwt.InvalidTokenError( f"Missing authorization header prefix '{self.http_header_prefix}'" ) else: # Strip off the prefix token = token.replace(f'{self.http_header_prefix} ', '') return token
def _ecommerce_jwt_decode_handler_multiple_issuers(token): """ Unlike the edx-drf-extensions jwt_decode_handler implementation, this jwt_decode_handler loops over multiple issuers using the same config format as the edx-drf-extensions decoder. Example:: JWT_AUTH: JWT_ISSUERS: - AUDIENCE: '{{ COMMON_JWT_AUDIENCE }}' ISSUER: '{{ COMMON_JWT_ISSUER }}' SECRET_KEY: '{{ COMMON_JWT_SECRET_KEY }}' See ARCH-276 for details of removing additional issuers and retiring this custom jwt_decode_handler. """ options = { 'verify_exp': api_settings.JWT_VERIFY_EXPIRATION, 'verify_aud': settings.JWT_AUTH['JWT_VERIFY_AUDIENCE'], } error_msg = '' # JWT_ISSUERS is not one of DRF-JWT's default settings, and cannot be accessed # using the `api_settings` object without overriding DRF-JWT's defaults. issuers = settings.JWT_AUTH['JWT_ISSUERS'] for issuer in issuers: try: return jwt.decode(token, issuer['SECRET_KEY'], api_settings.JWT_VERIFY, options=options, leeway=api_settings.JWT_LEEWAY, audience=issuer['AUDIENCE'], issuer=issuer['ISSUER'], algorithms=[api_settings.JWT_ALGORITHM]) except jwt.InvalidIssuerError: # Ignore these errors since we have multiple issuers error_msg += "Issuer {} does not match token. ".format( issuer['ISSUER']) except jwt.DecodeError: # Ignore these errors since we have multiple issuers error_msg += "Wrong secret_key for issuer {}. ".format( issuer['ISSUER']) except jwt.InvalidAlgorithmError: # pragma: no cover # These should all fail because asymmetric keys are not supported error_msg += "Algorithm not supported. " break except jwt.InvalidTokenError: error_msg += "Invalid token found using issuer {}. ".format( issuer['ISSUER']) logger.exception('Custom config JWT decode failed!') raise jwt.InvalidTokenError( 'All combinations of JWT issuers with updated config failed to validate the token. ' + error_msg)
def get(self): header_args = header_parser.parse_args() token = header_args['Authorization'].split(" ")[1] if token: if logout_user(token): return {'status': 'success'}, 200 else: return {'status': 'fail'}, 500 else: raise jwt.InvalidTokenError()
def _verify_version(jwt_version): supported_version = Version( settings.JWT_AUTH.get('JWT_SUPPORTED_VERSION', JwtTokenVersion.default_latest_supported)) if jwt_version.major > supported_version.major: logger.info( 'Token decode failed due to unsupported JWT version number [%s]', str(jwt_version)) raise jwt.InvalidTokenError( 'JWT version number [%s] is unsupported' % str(jwt_version))
def decode_token(token): '''decode access token from authorization header''' try: payload = jwt.decode(token, str(current_app.config.get('SECRET')), algorithms=['HS256']) return payload except Exception: # the token is invalid, return an error string raise jwt.InvalidTokenError( "Invalid token. Please register or login")
def decode_token(token): try: if Users.check_not_blacklisted(token): payload = jwt.decode(token, app.config['SECRET_KEY']) return payload['sub'] else: raise ValueError('Invalid token') except jwt.ExpiredSignatureError: raise jwt.ExpiredSignatureError() except jwt.InvalidTokenError: raise jwt.InvalidTokenError()
def get_subject(self, jwt_path): jwt_bu64 = self._read_jwt(jwt_path) try: jwt_dict = d1_common.cert.jwt.get_jwt_dict(jwt_bu64) except jwt.InvalidTokenError as e: raise django.core.management.base.CommandError( 'Unable to decode JWT. error="{}"'.format(str(e)) ) try: return jwt_dict['sub'] except KeyError: raise jwt.InvalidTokenError('Missing "sub" key')
def decode_auth_token(auth_token): if not auth_token or len(auth_token) == 0: raise Exception("auth_token is empty") try: payload = jwt.decode(auth_token, SECRET) return payload['sub'] except jwt.ExpiredSignatureError: raise jwt.ExpiredSignatureError('Signature expired') return 'Signature expired. Please log in again.' except jwt.InvalidTokenError: raise jwt.InvalidTokenError('Invalid token') return 'Invalid token. Please log in again.'
def authenticate(self, req, *args, **kwargs): token = self.get_token(req, *args, **kwargs) payload = self.decode(token) if self.verify_function: problem = self.verify_function(payload) if problem is not None: raise jwt.InvalidTokenError( f"Problematic JWT token '{problem}'") return payload
def decode_auth_token(auth_token): """ Validates the auth token :param auth_token: :return: integer|string """ payload = jwt.decode(auth_token, app.config.get('SECRET_KEY')) is_blacklisted_token = blacklist_token.check_blacklist_token(auth_token) if is_blacklisted_token: raise jwt.InvalidTokenError('Please re-login to access the page') else: return payload['sub']