Python jwt.DecodeError() Examples
The following are 30
code examples of jwt.DecodeError().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
jwt
, or try the search function
.
Example #1
Source File: validator.py From django-cognito-jwt with MIT License | 9 votes |
def validate(self, token): public_key = self._get_public_key(token) if not public_key: raise TokenError("No key found for this token") try: jwt_data = jwt.decode( token, public_key, audience=self.audience, issuer=self.pool_url, algorithms=["RS256"], ) except (jwt.InvalidTokenError, jwt.ExpiredSignature, jwt.DecodeError) as exc: raise TokenError(str(exc)) return jwt_data
Example #2
Source File: service.py From lemur with Apache License 2.0 | 7 votes |
def fetch_token_header(token): """ Fetch the header out of the JWT token. :param token: :return: :raise jwt.DecodeError: """ token = token.encode("utf-8") try: signing_input, crypto_segment = token.rsplit(b".", 1) header_segment, payload_segment = signing_input.split(b".", 1) except ValueError: raise jwt.DecodeError("Not enough segments") try: return json.loads(jwt.utils.base64url_decode(header_segment).decode("utf-8")) except TypeError as e: current_app.logger.exception(e) raise jwt.DecodeError("Invalid header padding")
Example #3
Source File: authentication.py From django-oauth-toolkit-jwt with MIT License | 6 votes |
def authenticate(self, request): """ Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based authentication. Otherwise returns `None`. """ jwt_value = self._get_jwt_value(request) if jwt_value is None: return None try: payload = decode_jwt(jwt_value) except jwt.ExpiredSignatureError: msg = 'Signature has expired.' raise exceptions.AuthenticationFailed(msg) except jwt.DecodeError: msg = 'Error decoding signature.' raise exceptions.AuthenticationFailed(msg) except jwt.InvalidTokenError: raise exceptions.AuthenticationFailed() self._add_session_details(request, payload) user = self.authenticate_credentials(payload) return user, JwtToken(payload)
Example #4
Source File: azuread_tenant.py From Dailyfresh-B2C with Apache License 2.0 | 6 votes |
def get_certificate(self, kid): # retrieve keys from jwks_url resp = self.request(self.jwks_url(), method='GET') resp.raise_for_status() # find the proper key for the kid for key in resp.json()['keys']: if key['kid'] == kid: x5c = key['x5c'][0] break else: raise DecodeError('Cannot find kid={}'.format(kid)) certificate = '-----BEGIN CERTIFICATE-----\n' \ '{}\n' \ '-----END CERTIFICATE-----'.format(x5c) return load_pem_x509_certificate(certificate.encode(), default_backend())
Example #5
Source File: azuread_tenant.py From Dailyfresh-B2C with Apache License 2.0 | 6 votes |
def user_data(self, access_token, *args, **kwargs): response = kwargs.get('response') id_token = response.get('id_token') # decode the JWT header as JSON dict jwt_header = json.loads( base64.b64decode(id_token.split('.', 1)[0]).decode() ) # get key id and algorithm key_id = jwt_header['kid'] algorithm = jwt_header['alg'] try: # retrieve certificate for key_id certificate = self.get_certificate(key_id) return jwt_decode( id_token, key=certificate.public_key(), algorithms=algorithm, audience=self.setting('SOCIAL_AUTH_AZUREAD_OAUTH2_KEY') ) except (DecodeError, ExpiredSignature) as error: raise AuthTokenError(self, error)
Example #6
Source File: connection.py From FlowKit with Mozilla Public License 2.0 | 6 votes |
def update_token(self, token: str) -> None: """ Replace this connection's API token with a new one. Parameters ---------- token : str JSON Web Token for this API server """ try: self.user = jwt.decode(token, verify=False)["identity"] except jwt.DecodeError: raise FlowclientConnectionError(f"Unable to decode token: '{token}'") except KeyError: raise FlowclientConnectionError(f"Token does not contain user identity.") self.token = token self.session.headers["Authorization"] = f"Bearer {self.token}"
Example #7
Source File: validator.py From django-cognito-jwt with MIT License | 6 votes |
def _get_public_key(self, token): try: headers = jwt.get_unverified_header(token) except jwt.DecodeError as exc: raise TokenError(str(exc)) if getattr(settings, "COGNITO_PUBLIC_KEYS_CACHING_ENABLED", False): cache_key = "django_cognito_jwt:%s" % headers["kid"] jwk_data = cache.get(cache_key) if not jwk_data: jwk_data = self._json_web_keys.get(headers["kid"]) timeout = getattr(settings, "COGNITO_PUBLIC_KEYS_CACHING_TIMEOUT", 300) cache.set(cache_key, jwk_data, timeout=timeout) else: jwk_data = self._json_web_keys.get(headers["kid"]) if jwk_data: return RSAAlgorithm.from_jwk(jwk_data)
Example #8
Source File: authentication.py From django-rest-framework-jwt with MIT License | 6 votes |
def authenticate(self, request): """ Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based authentication. Otherwise returns `None`. """ jwt_value = self.get_jwt_value(request) if jwt_value is None: return None try: payload = jwt_decode_handler(jwt_value) except jwt.ExpiredSignature: msg = _('Signature has expired.') raise exceptions.AuthenticationFailed(msg) except jwt.DecodeError: msg = _('Error decoding signature.') raise exceptions.AuthenticationFailed(msg) except jwt.InvalidTokenError: raise exceptions.AuthenticationFailed() user = self.authenticate_credentials(payload) return (user, payload)
Example #9
Source File: azuread_b2c.py From Dailyfresh-B2C with Apache License 2.0 | 6 votes |
def user_data(self, access_token, *args, **kwargs): response = kwargs.get('response') id_token = response.get('id_token') if six.PY2: # str() to fix a bug in Python's base64 # https://stackoverflow.com/a/2230623/161278 id_token = str(id_token) jwt_header_json = base64url_decode(id_token.split('.')[0]) jwt_header = json.loads(jwt_header_json.decode('ascii')) # `kid` is short for key id key = self.get_public_key(jwt_header['kid']) try: return jwt_decode( id_token, key=key, algorithms=jwt_header['alg'], audience=self.setting('KEY'), leeway=self.setting('JWT_LEEWAY', default=0), ) except (DecodeError, ExpiredSignature) as error: raise AuthTokenError(self, error)
Example #10
Source File: api.py From flask-restful-authentication with GNU General Public License v3.0 | 6 votes |
def login_required(method): @functools.wraps(method) def wrapper(self): header = request.headers.get('Authorization') _, token = header.split() try: decoded = jwt.decode(token, app.config['KEY'], algorithms='HS256') except jwt.DecodeError: abort(400, message='Token is not valid.') except jwt.ExpiredSignatureError: abort(400, message='Token is expired.') email = decoded['email'] if db.users.find({'email': email}).count() == 0: abort(400, message='User is not found.') user = db.users.find_one({'email': email}) return method(self, user) return wrapper
Example #11
Source File: course_activity_planner.py From course-activity-planner with GNU General Public License v3.0 | 6 votes |
def login_req(f): @wraps(f) def decorated_func(*args, **kwargs): if not request.headers.get('Authorization'): return jsonify(message='Please login'), 401 try: payload = _parse_token_from_header(request) g.user_id = payload['sub'] return f(*args, **kwargs) except DecodeError: return jsonify(message='Your session is invalid'), 401 except ExpiredSignature: return jsonify(message='\ Your session has expired. Please login again.'), 401 return decorated_func
Example #12
Source File: tokenizer.py From blockstack-auth-python with MIT License | 6 votes |
def verify(self, token, verifying_key): # grab the token parts token_parts = self._unpack(token) header, payload, raw_signature, signing_input = token_parts # load the verifying key verifying_key = load_verifying_key(verifying_key, self.crypto_backend) # convert the raw_signature to DER format der_signature = raw_to_der_signature( raw_signature, verifying_key.curve) # initialize the verifier verifier = self._get_verifier(verifying_key, der_signature) verifier.update(signing_input) # check to see whether the signature is valid try: verifier.verify() except InvalidSignature: # raise DecodeError('Signature verification failed') return False return True
Example #13
Source File: jwtAuth.py From django-RESTfulAPI with MIT License | 6 votes |
def authenticate(self, request): """ Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based authentication. Otherwise returns `None`. """ jwt_value = self.get_jwt_value(request) if jwt_value is None: return None try: payload = jwt_decode_handler(jwt_value) except jwt.ExpiredSignature: msg = 'Token过期' raise exceptions.AuthenticationFailed({"message": msg,"errorCode":1,"data":{}}) except jwt.DecodeError: msg = 'Token不合法' raise exceptions.AuthenticationFailed({"message": msg,"errorCode":1,"data":{}}) except jwt.InvalidTokenError: raise exceptions.AuthenticationFailed() user = self.authenticate_credentials(payload) return user, jwt_value
Example #14
Source File: BaseMiddleWare.py From django-RESTfulAPI with MIT License | 6 votes |
def process_request(self, request): if request.META.get('HTTP_AUTHORIZATION'): token = (request.META.get('HTTP_AUTHORIZATION').split(' '))[1] try: payload = jwt_decode_handler(token) user_id = jwt_get_user_id_from_payload_handler(payload) if not user_id: return JsonResponse({"message": "用户不存在!" , "errorCode": 2, "data": {}}) now_user = User.objects.values('id', 'is_freeze').filter(id=user_id).first() if not now_user: return JsonResponse({"message": "用户不存在!" , "errorCode": 2, "data": {}}) if now_user.get('is_freeze'): return JsonResponse({"message": "账户被冻结!", "errorCode": 2, "data": {}}) except jwt.ExpiredSignature: return JsonResponse({"message": 'Token过期' , "errorCode": 2, "data": {}}) except jwt.DecodeError: return JsonResponse({"message": 'Token不合法' , "errorCode": 2, "data": {}}) except jwt.InvalidTokenError as e: return JsonResponse({"message": "出现了无法预料的view视图错误:%s" % e, "errorCode": 1, "data": {}})
Example #15
Source File: jwt_manager.py From PROTON with BSD 3-Clause "New" or "Revised" License | 6 votes |
def authenticate(cls, jwt_token): """ Validates if JWT Token still stands True. :param jwt_token: JWT Token issued by generate_token method :return: A dict containing status and payload on success """ if jwt_token: try: payload = jwt.decode(jwt_token, cls.app_secret) except (jwt.DecodeError, jwt.ExpiredSignatureError) as e: cls.token_authenticator_logger.exception( '[JWT Manager]: Authentication failed due to : {}'.format(str(e))) return { 'status': False, 'message': 'Token invalid {}'.format(str(e)), 'encode_value': None } cls.token_authenticator_logger.info('[JWT Manager]: Authentication succeded.') return { 'status': True, 'message': 'Token valid', 'encode_value': payload['encode_value'] }
Example #16
Source File: crackjwt.py From jwtcrack with GNU Affero General Public License v3.0 | 5 votes |
def crack_jwt(jwt, dictionary): header = get_unverified_header(jwt) with open(dictionary) as fp: for secret in tqdm(fp): secret = secret.rstrip() try: decode(jwt, secret, algorithms=[header["alg"]]) return secret except DecodeError: # Signature verification failed pass except InvalidTokenError: # Signature correct, something else failed return secret
Example #17
Source File: api.py From flask-restful-authentication with GNU General Public License v3.0 | 5 votes |
def put(self): activation_code = request.json['activation_code'] try: decoded = jwt.decode(activation_code, app.config['KEY'], algorithms='HS256') except jwt.DecodeError: abort(400, message='Activation code is not valid.') except jwt.ExpiredSignatureError: abort(400, message='Activation code is expired.') email = decoded['email'] db.users.update({'email': email}, {'$set': {'active': True}}) return {'email': email}
Example #18
Source File: mixins.py From django-jwt-auth with MIT License | 5 votes |
def authenticate(self, request): auth = get_authorization_header(request).split() auth_header_prefix = settings.JWT_AUTH_HEADER_PREFIX.lower() if not auth or smart_text(auth[0].lower()) != auth_header_prefix: raise exceptions.AuthenticationFailed() if len(auth) == 1: msg = 'Invalid Authorization header. No credentials provided.' raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = ('Invalid Authorization header. Credentials string ' 'should not contain spaces.') raise exceptions.AuthenticationFailed(msg) try: payload = jwt_decode_handler(auth[1]) except jwt.ExpiredSignature: msg = 'Signature has expired.' raise exceptions.AuthenticationFailed(msg) except jwt.DecodeError: msg = 'Error decoding signature.' raise exceptions.AuthenticationFailed(msg) user = self.authenticate_credentials(payload) return (user, auth[1])
Example #19
Source File: webauth.py From Tautulli with GNU General Public License v3.0 | 5 votes |
def check_jwt_token(): jwt_cookie = str(JWT_COOKIE_NAME + plexpy.CONFIG.PMS_UUID) jwt_token = cherrypy.request.cookie.get(jwt_cookie) if jwt_token: try: payload = jwt.decode( jwt_token.value, plexpy.CONFIG.JWT_SECRET, leeway=timedelta(seconds=10), algorithms=[JWT_ALGORITHM] ) except (jwt.DecodeError, jwt.ExpiredSignatureError): return None return payload
Example #20
Source File: tokenizer.py From blockstack-auth-python with MIT License | 5 votes |
def _unpack(cls, token): if isinstance(token, (str, unicode)): token = token.encode('utf-8') try: signing_input, crypto_segment = token.rsplit(b'.', 1) header_segment, payload_segment = signing_input.split(b'.', 1) except ValueError: raise DecodeError('Not enough segments') try: header_data = base64url_decode(header_segment) except (TypeError, binascii.Error): raise DecodeError('Invalid header padding') try: header = json.loads(header_data.decode('utf-8')) except ValueError as e: raise DecodeError('Invalid header string: %s' % e) if not isinstance(header, Mapping): raise DecodeError('Invalid header string: must be a json object') try: payload_data = base64url_decode(payload_segment) except (TypeError, binascii.Error): raise DecodeError('Invalid payload padding') try: payload = json.loads(payload_data.decode('utf-8')) except ValueError as e: raise DecodeError('Invalid payload string: %s' % e) try: signature = base64url_decode(crypto_segment) except (TypeError, binascii.Error): raise DecodeError('Invalid crypto padding') return header, payload, signature, signing_input
Example #21
Source File: azuread.py From Dailyfresh-B2C with Apache License 2.0 | 5 votes |
def user_data(self, access_token, *args, **kwargs): response = kwargs.get('response') id_token = response.get('id_token') try: decoded_id_token = jwt_decode(id_token, verify=False) except (DecodeError, ExpiredSignature) as de: raise AuthTokenError(self, de) return decoded_id_token
Example #22
Source File: microsoft.py From Dailyfresh-B2C with Apache License 2.0 | 5 votes |
def user_data(self, access_token, *args, **kwargs): """Return user data by querying Microsoft service""" try: return self.get_json( 'https://graph.microsoft.com/v1.0/me', headers={ 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json', 'Authorization': 'Bearer ' + access_token }, method='GET' ) except (DecodeError, ExpiredSignature) as error: raise AuthTokenError(self, error)
Example #23
Source File: auth_message.py From blockstack-auth-python with MIT License | 5 votes |
def verify(cls, token, tokenizer=Tokenizer()): # decode the token try: decoded_token = cls.decode(token) except DecodeError: traceback.print_exc() return False return all([method(token, tokenizer, decoded_token) for method in cls.verify_methods])
Example #24
Source File: exacttarget.py From Dailyfresh-B2C with Apache License 2.0 | 5 votes |
def do_auth(self, token, *args, **kwargs): dummy, secret = self.get_key_and_secret() try: # Decode the token, using the Application Signature from settings decoded = jwt.decode(token, secret, algorithms=['HS256']) except jwt.DecodeError: # Wrong signature, fail authentication raise AuthCanceled(self) kwargs.update({'response': {'token': decoded}, 'backend': self}) return self.strategy.authenticate(*args, **kwargs)
Example #25
Source File: wrappers.py From cloud-inquisitor with Apache License 2.0 | 5 votes |
def __check_auth(self, view): headers = {x[0]: x[1] for x in request.headers} if 'Authorization' in headers: try: token = jwt.decode( headers['Authorization'], get_jwt_key_data() ) if token['auth_system'] != current_app.active_auth_system.name: self.log.error('Token is from another auth_system ({}) than the current one ({})'.format( token['auth_system'], current_app.active_auth_system.name )) return view.make_unauth_response() if has_access(session['user'], self.role): return self.log.error('User {} attempted to access page {} without permissions'.format( session['user'].username, request.path )) return view.make_unauth_response() except (jwt.DecodeError, jwt.ExpiredSignatureError) as ex: session.clear() view.log.info('Failed to decode signature or it had expired: {0}'.format(ex)) return view.make_unauth_response() session.clear() view.log.info('Failed to detect Authorization header') return view.make_unauth_response()
Example #26
Source File: views.py From impactstory-tng with MIT License | 5 votes |
def login_required(f): @wraps(f) def decorated_function(*args, **kwargs): if not request.headers.get('Authorization'): response = jsonify(message='Missing authorization header') print u"in login_required with error, Missing authorization header" response.status_code = 401 return response try: payload = parse_token(request) except DecodeError: response = jsonify(message='Token is invalid') response.status_code = 401 print u"in login_required with error, got DecodeError" return response except ExpiredSignature: response = jsonify(message='Token has expired') response.status_code = 401 print u"in login_required with error, got DecodeError" return response # print u"in login_required. payload: {}: ".format(payload) g.my_person = None if "id" in payload: # this uses the current token format g.my_person = Person.query.filter_by(id=payload["id"]).first() if not g.my_person and "orcid_id" in payload: # fallback because some tokens don't have id? g.my_person = Person.query.filter_by(orcid_id=payload["orcid_id"]).first() if not g.my_person and "sub" in payload: # fallback for old token format g.my_person = Person.query.filter_by(orcid_id=payload["sub"]).first() if not g.my_person: print u"in login_required with error, no known keys in token payload: {}".format(payload) # print u"in login_required success, got a person {}".format(g.my_person) return f(*args, **kwargs) return decorated_function
Example #27
Source File: auth.py From ok with Apache License 2.0 | 5 votes |
def microsoft_user_data(token): """ Query Microsoft for a user's info. """ if not token: logger.info("Microsoft Token is None") return None try: decoded_token = jwt.decode(token, verify=False) if 'unique_name' in decoded_token: # azure ad unique id logger.info("token found in Azure unique_name value") return {'email': decoded_token['unique_name']} if 'upn' in decoded_token: # fallback to upn logger.info("token found in Azure upn value") return {'email': decoded_token['upn']} # reading from the Token didn't work - now we try a MS Graph Call. logger.warning("token had no values and MS Graph WILL be called") headers = {'Accept': 'application/json', 'Authorization': 'Bearer ' + token} r = requests.get(current_app.config.get(provider_name)['base_url'] + '/me', headers=headers) ms_graph_me = r.json() if 'userPrincipalName' in ms_graph_me: logger.warning("token had no values and MS Graph call made!") return { 'email': ms_graph_me['userPrincipalName']} logger.error("Unable to retrieve unique_name (the user's email) from token") return None except jwt.DecodeError as e: logger.error("jwt decode error from token") logger.error('Decode error was %s', e) return None
Example #28
Source File: keycloak.py From vitrage with Apache License 2.0 | 5 votes |
def _decode(self, token): try: return jwt.decode(token, algorithms=['RS256'], verify=False) except jwt.DecodeError: message = "Token can't be decoded because of wrong format." self._unauthorized(message)
Example #29
Source File: prepolicy.py From privacyidea with GNU Affero General Public License v3.0 | 5 votes |
def api_key_required(request=None, action=None): """ This is a decorator for check_user_pass and check_serial_pass. It checks, if a policy scope=auth, action=apikeyrequired is set. If so, the validate request will only performed, if a JWT token is passed with role=validate. """ user_object = request.User # Get the policies action = Match.user(g, scope=SCOPE.AUTHZ, action=ACTION.APIKEY, user_object=user_object).policies() # Do we have a policy? if action: # check if we were passed a correct JWT # Get the Authorization token from the header auth_token = request.headers.get('PI-Authorization') if not auth_token: auth_token = request.headers.get('Authorization') try: r = jwt.decode(auth_token, current_app.secret_key, algorithms=['HS256']) g.logged_in_user = {"username": r.get("username", ""), "realm": r.get("realm", ""), "role": r.get("role", "")} except (AttributeError, jwt.DecodeError): # PyJWT 1.3.0 raises AttributeError, PyJWT 1.6.4 raises DecodeError. raise PolicyError("No valid API key was passed.") role = g.logged_in_user.get("role") if role != ROLE.VALIDATE: raise PolicyError("A correct JWT was passed, but it was no API " "key.") # If everything went fine, we call the original function return True
Example #30
Source File: __init__.py From ga4gh-server with Apache License 2.0 | 5 votes |
def _decode_header(auth_header, client_id, client_secret): """ Takes the header and tries to return an active token and decoded payload. :param auth_header: :param client_id: :param client_secret: :return: (token, profile) """ try: token = auth_header.split()[1] payload = jwt.decode( token, client_secret, audience=client_id) except jwt.ExpiredSignature: raise exceptions.NotAuthorizedException( 'Token has expired, please log in again.') # is valid client except jwt.InvalidAudienceError: message = 'Incorrect audience, expected: {}'.format( client_id) raise exceptions.NotAuthorizedException(message) # is valid token except jwt.DecodeError: raise exceptions.NotAuthorizedException( 'Token signature could not be validated.') except Exception as e: raise exceptions.NotAuthorizedException( 'Token signature was malformed. {}'.format(e.message)) return token, payload