def get_claims(token: str) -> Dict[str, Union[str, int]]: # get the kid from the headers prior to verification headers: Dict[str, str] = cast(Dict[str, str], jwt.get_unverified_headers(token=token)) kid: str = headers["kid"] # search for the kid in the downloaded public keys for key in _get_keys(): if kid == key["kid"]: # construct the public key public_key = jwk.construct(key_data=key) break else: raise ValueError("Public key not found in JWK.") # get the last two sections of the token, # message and signature (encoded in base64) message, encoded_signature = token.rsplit(".", 1) # decode the signature decoded_signature: bytes = base64url_decode(encoded_signature.encode("utf-8")) # verify the signature if public_key.verify(msg=message.encode("utf8"), sig=decoded_signature) is False: raise RuntimeError("Signature verification failed.") print("Signature validaded.") # since we passed the verification, we can now safely use the unverified claims claims: Dict[str, Union[str, int]] = cast(Dict[str, Union[str, int]], jwt.get_unverified_claims(token)) # additionally we can verify the token expiration if time.time() > int(claims["exp"]): raise ValueError("Token expired.") print("Token not expired.") # and the Audience (use claims['client_id'] if verifying an access token) if claims["aud"] != COGNITO_USER_POOL_CLIENT_ID: raise ValueError("Token was not issued for this audience.") # now we can use the claims return claims
def fetch_jwt_public_key_for(id_token=None): if id_token is None: raise NameError('id_token is required') dirty_header = jws.get_unverified_header(id_token) cleaned_key_id = None if 'kid' in dirty_header: dirty_key_id = dirty_header['kid'] cleaned_key_id = re.sub(not_alpha_numeric, '', dirty_key_id) else: raise ValueError('The id_token header must contain a "kid"') if cleaned_key_id in public_keys: return public_keys[cleaned_key_id] unverified_claims = jwt.get_unverified_claims(id_token) dirty_url = urlparse.urlparse(unverified_claims['iss']) if domain_name_for(dirty_url) not in allowed_domains: raise ValueError('The domain in the issuer claim is not allowed') cleaned_issuer = dirty_url.geturl() oidc_discovery_url = "{}/.well-known/openid-configuration".format( cleaned_issuer) r = requests.get(oidc_discovery_url) openid_configuration = r.json() jwks_uri = openid_configuration['jwks_uri'] r = requests.get(jwks_uri) jwks = r.json() for key in jwks['keys']: jwk_id = key['kid'] public_keys[jwk_id] = key if cleaned_key_id in public_keys: return public_keys[cleaned_key_id] else: raise RuntimeError("Unable to fetch public key from jwks_uri")
def on_join(message): cookie = request.cookies.get("oidc-jwt", None) if cookie is None: emit('joinRoomFail', {"sucess": False}) return if not oidc.validate_token(cookie): print("Cookie failed validation") emit('joinRoomFail', {"sucess": False}) return claims = jwt.get_unverified_claims(cookie) if claims["preferred_username"]: csr = CSR.find_by_username(claims["preferred_username"]) if csr: join_room(csr.office_id) emit('joinRoomSuccess', {"sucess": True}) emit('get_Csr_State_IDs', {"success": True}) emit('update_customer_list', {"success": True}) else: print("Fail") emit('joinRoomFail', {"success": False}) else: print("No preferred_username on request") emit('joinRoomFail', {"success": False})
def wrapper(*args, **kwargs): token = get_token_auth_header() try: user_id = jwt.get_unverified_claims(token)["sub"] except BaseException: abort(401) return f(user_id)
async def __call__( self, http_auth: HTTPAuthorizationCredentials = Depends(HTTPBearer()) ) -> Optional[Type[BaseModel]]: """Get current user and verification with ID-token Shortcut. Use as (`Auth` is this subclass, `auth` is `Auth` instanse and `app` is fastapi.FastAPI instanse): ``` from fastapi import Depends @app.get("/") def api(current_user: Auth = Depends(auth)): return current_user ``` """ is_verified = self.verify_token(http_auth) if not is_verified: return None claims = jwt.get_unverified_claims(http_auth.credentials) try: current_user = self.user_info.parse_obj(claims) return current_user except ValidationError: if self.auto_error: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Validation Error for Claims", ) else: return None
def is_authenticated(request): try : token = get_token_auth_header(request) claims = jwt.get_unverified_claims(token) return claims['exp'] > datetime.datetime.now().toordinal() except AttributeError: return request.user.is_authenticated
def token_decoder(token): set_cognito_data_global() headers = jwt.get_unverified_headers(token) kid = headers['kid'] result = {} for item in POOL_KEYS: result[item['kid']] = item public_key = jwk.construct(result.get(kid)) message, encoded_signature = str(token).rsplit('.', 1) decoded_signature = base64url_decode(encoded_signature.encode('utf-8')) if not public_key.verify(message.encode("utf8"), decoded_signature): app.logger.error('Signature verification failed') raise Exception app.logger.debug('Signature successfully verified') claims = jwt.get_unverified_claims(token) if time.time() > claims['exp']: app.logger.error('Token is expired') raise Exception app.logger.debug(claims) return claims
def main(j, args, params, tags, tasklet): from jose import jwt as jose_jwt from JumpScale.portal.portal import exceptions import json params.result = (args.doc, args.doc) node_id = args.requestContext.params.get('node') remote = None data = {} if node_id: node_name, remote = j.apps.cloudbroker.zeroaccess._get_node_info(node_id) data['name'] = node_name oauth = j.clients.oauth.get(instance='itsyouonline') try: jwt = oauth.get_active_jwt(session=args.requestContext.env['beaker.session']) except: raise exceptions.NotFound('Page not found') if jwt: jwt_data = jose_jwt.get_unverified_claims(jwt) jwt_data = json.loads(jwt_data) scope = "user:memberof:{}.0-access".format(oauth.id) if scope not in jwt_data['scope']: raise exceptions.NotFound('Page not found') table_data = j.apps.cloudbroker.zeroaccess.listSessions(remote=remote, ctx=args.requestContext) else: table_data = [['No jwt found please logout and login again', '', '', '', '']] if not table_data: table_data = [['No sessions found', '', '', '', '']] data['tables'] = table_data args.doc.applyTemplate(data, False) return params
def get(self): cookie = request.cookies.get("oidc-jwt", None) if cookie is None: return abort(401, self.auth_string) if not oidc.validate_token(cookie): return abort(401, self.auth_string) claims = jwt.get_unverified_claims(cookie) if claims["preferred_username"]: csr = CSR.find_by_username(claims["preferred_username"]) if csr: if csr.deleted is None: csr.is_active = True else: csr.is_active = False csr.is_authenticated = False csr.is_anonymous = False login_user(csr) if application.config['USE_HTTPS']: return redirect(url_for("admin.index", _scheme=application.config['PREFERRED_URL_SCHEME'], _external=application.config['USE_HTTPS'])) else: return redirect(url_for("admin.index")) else: return abort(401, self.auth_string) else: return abort(401, self.auth_string)
def add_test_user( username=f"test_user{info.major}{info.minor}@example.com", password="******", scope: Optional[str] = None, ): resp = requests.post( f"https://{DOMAIN}/dbconnections/signup", { "client_id": CLIENTID, "email": username, "password": password, "connection": CONNECTION, "username": username, }, ) access_token, _ = get_access_token() user_id = jwt.get_unverified_claims(access_token)["sub"] default_token = get_default_access_token() resp = requests.post( f"https://{DOMAIN}/api/v2/users/{user_id}/permissions", headers={ "authorization": f"Bearer {default_token}", "cache-control": "no-cache", }, data={ "permissions": [{ "resource_server_identifier": f"https://{DOMAIN}/api/v2/", "permission_name": scope, }] }, )
def verify_user(access, refresh, id): u = Cognito(CONSTANTS['cognito_id'], CONSTANTS['cognito_app'], id_token=id, refresh_token=refresh, access_token=access) if (not u.check_token() is None): id_info = jwt.get_unverified_claims(id) access_info = jwt.get_unverified_claims(access) if id_info.get('sub') == access_info.get( 'username') and access_info.get( 'client_id') == CONSTANTS['cognito_app']: return True, id_info.get('email') else: return False, None return False, None
def cla_user(default=None, request=None, **kwargs): """Returns the current logged in CLA user""" headers = request.headers if headers is None: cla.log.error('Error reading headers') return default bearer_token = headers.get('Authorization') or headers.get('AUTHORIZATION') if bearer_token is None: cla.log.error('Error reading authorization header') return default bearer_token = bearer_token.replace('Bearer ', '') try: token_params = jwt.get_unverified_claims(bearer_token) except Exception as e: cla.log.error('Error parsing Bearer token: {}'.format(e)) return default if token_params is not None: return CLAUser(token_params) cla.log.error('Failed to get user information from request') return default
async def call( self, http_auth: HTTPAuthorizationCredentials ) -> Optional[Union[BaseModel, Dict[str, Any]]]: """Get current user and verification with ID-token Shortcut. Use as (`Auth` is this subclass, `auth` is `Auth` instanse and `app` is fastapi.FastAPI instanse): ``` from fastapi import Depends @app.get("/") def api(current_user: Auth = Depends(auth)): return current_user ``` """ claims: Dict[str, Any] = jwt.get_unverified_claims(http_auth.credentials) if not self.user_info: return claims try: current_user = self.user_info.parse_obj(claims) return current_user except ValidationError: if self.auto_error: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail=NOT_VALIDATED_CLAIMS, ) else: return None
def requires_scope(required_scope): token = get_token_auth_header() unverified_claims = jwt.get_unverified_claims(token) guser_perms = unverified_claims.get("permissions") for u in guser_perms: print("permisions "+u) return Response(json.dumps(guser_perms), mimetype='application/json')
def get_user_group_from_id_token(cls, event): # Workaround until we found a solution to deploy cognito locally if os.environ.get('IS_OFFLINE') is not None: return [os.environ.get('LOCAL_USER_GROUP')] token = cls.get_token_from_event(event) payload = jwt.get_unverified_claims(token) return payload.get('cognito:groups')
async def __call__( self, request: Request) -> Optional[JWTAuthorizationCredentials]: credentials: HTTPAuthorizationCredentials = await super().__call__( request) if credentials: if not credentials.scheme == "Bearer": raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="Wrong authentication method") jwt_token = credentials.credentials message, signature = jwt_token.rsplit(".", 1) try: jwt_credentials = JWTAuthorizationCredentials( jwt_token=jwt_token, header=jwt.get_unverified_header(jwt_token), claims=jwt.get_unverified_claims(jwt_token), signature=signature, message=message, ) except JWTError: raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="JWK invalid") if not self.verify_jwk_token(jwt_credentials): raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="JWK invalid") return jwt_credentials
def on_join(message): cookie = request.cookies.get("oidc-jwt", None) if cookie is None: emit('joinRoomFail', {"sucess": False}) return if not oidc.validate_token(cookie): print("Cookie failed validation") emit('joinRoomFail', {"sucess": False}) return claims = jwt.get_unverified_claims(cookie) if claims["preferred_username"]: print( "==> In Python, @socketio.on('joinRoom'): claims['preferred_username'] is: " + str(claims["preferred_username"])) csr = CSR.find_by_username(claims["preferred_username"]) if csr: join_room(csr.office_id) print("==> In websocket.py, CSR joinroom, CSR: " + csr.username + "; request sid: " + str(request.sid)) emit('joinRoomSuccess', {"sucess": True}) emit('get_Csr_State_IDs', {"success": True}) emit('update_customer_list', {"success": True}) else: print("Fail") emit('joinRoomFail', {"success": False}) else: print("No preferred_username on request") emit('joinRoomFail', {"success": False})
def lambda_handler(event, context): token = event['token'] # get the kid from the headers prior to verification headers = jwt.get_unverified_headers(token) kid = headers['kid'] # search for the kid in the downloaded public keys key_index = -1 for i in range(len(keys)): if kid == keys[i]['kid']: key_index = i break if key_index == -1: print('Public key not found in jwks.json') return False # construct the public key public_key = jwk.construct(keys[key_index]) # get the last two sections of the token, # message and signature (encoded in base64) message, encoded_signature = str(token).rsplit('.', 1) # decode the signature decoded_signature = base64url_decode(encoded_signature) # verify the signature if public_key.verify(message, decoded_signature): print('Signature successfully verified') # since we passed the verification, now we can safely # get the unverified claims claims = jwt.get_unverified_claims(token) # do some stuff with our claims print(claims) return claims else: print('Signature verification failed') return False
def verify_id_token(id_token): keys = GoogleKeys.fetch_public_keys() headers = jwt.get_unverified_header(id_token) #print '--- headers ---' #print headers #print '--- claims ---' claims = json.loads(jwt.get_unverified_claims(id_token)) #print claims error_message = None if not headers.get('kid'): error_message = 'Firebase Auth ID token has no "kid" claim' elif headers.get('alg') != ALGORITHM: error_message = 'Firebase Auth ID token has incorrect algorithm' elif claims.get('aud') != PROJECT_ID: error_message = 'Firebase Auth ID token has incorrect "aud" claim' elif claims.get('iss') != 'https://securetoken.google.com/' + PROJECT_ID: error_message = 'Firebase Auth ID token has incorrect "iss" claim' elif not claims.get('sub') or len(claims['sub']) > 128: error_message = 'Firebase Auth ID token has invalid "sub" claim' if error_message: raise Exception(error_message) key = cert_to_public_rsa_key(keys[headers['kid']]) result = jwt.decode(id_token, key, algorithms=[ALGORITHM], audience=PROJECT_ID) #print '--- verification ---' #print result return result
def request_logging(cls, request): """ utility method to log the details of a request """ log = functools.partial(cls.REQUEST_LOGGING_LOGGER.log, cls.REQUEST_LOGGING_LEVEL) pattern = cls.REQUEST_LOGGING_OBFUSCATE_PATTERN data, headers = {}, {} for k, v in request.data.items(): if pattern.match(k): v = cls.obfuscate(v) data[k] = v for k, v in request._request.headers.items(): # pylint: disable=protected-access if pattern.match(k): try: token = v.split()[-1] v = { 'jwt_headers': jose_jwt.get_unverified_header(token), 'jwt_claims': jose_jwt.get_unverified_claims(token), } except (jose_exceptions.JOSEError, IndexError): v = cls.obfuscate(v) headers[k] = v msg = { 'path': request._request.path, # pylint: disable=protected-access 'query params': dict(request.query_params), 'data': data, 'headers': headers, } log(f'REQUEST => {json.dumps(msg, indent=2)}')
async def call( self, http_auth: HTTPAuthorizationCredentials ) -> Optional[Union[Dict[str, Any], BaseModel, bool]]: """User access-token verification Shortcut to pass it into dependencies. Use as (`auth` is this instanse and `app` is fastapi.FastAPI instanse): ``` from fastapi import Depends @app.get("/", dependencies=[Depends(auth)]) def api(): return "hello" ``` """ claims: Dict[str, Any] = jwt.get_unverified_claims(http_auth.credentials) if not self.user_info: return claims try: current_user = self.user_info.parse_obj(claims) return current_user except ValidationError: if self.auto_error: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail=NOT_VALIDATED_CLAIMS, ) else: return None
def on_join(message): cookie = request.cookies.get("oidc-jwt", None) if cookie is None: emit('joinRoomFail', {"sucess": False}) return if not oidc.validate_token(cookie): print("Cookie failed validation") emit('joinRoomFail', {"sucess": False}) return claims = jwt.get_unverified_claims(cookie) if claims["preferred_username"]: csr = CSR.query.filter_by( username=claims["preferred_username"].split("idir/")[-1]).first() if csr: join_room(csr.office_id) emit('joinRoomSuccess', {"sucess": True}) emit('update_customer_list', {"success": True}) print("Success") else: print("Fail") emit('joinRoomFail', {"success": False}) else: print("No preferred_username on request") emit('joinRoomFail', {"success": False})
def do_login(self): self.login.go() if self.home.is_here(): return self.page.login(self.username, self.password, self.lastname) if not self.home.is_here(): raise BrowserIncorrectPassword() # after login we need to get some tokens to use bouygues api data = { 'response_type': 'id_token token', 'client_id': 'a360.bouyguestelecom.fr', 'redirect_uri': 'https://www.bouyguestelecom.fr/mon-compte/' } self.location('https://oauth2.bouyguestelecom.fr/authorize', params=data) parsed_url = urlparse(self.response.url) fragment = parse_qs(parsed_url.fragment) if not fragment: query = parse_qs(parsed_url.query) if 'server_error' in query.get('error', []): raise BrowserUnavailable(query['error_description'][0]) claims = jwt.get_unverified_claims(fragment['id_token'][0]) self.headers = {'Authorization': 'Bearer %s' % fragment['access_token'][0]} self.id_user = claims['id_personne']
def add_new_collection(): if not request.headers.get('Authorization'): abort(401) access_token = request.headers.get('Authorization').split(' ').pop() print('Access Token', access_token) collection_name = request.get_json()["name"] print(collection_name) decoded_access_token = jwt.get_unverified_claims(access_token) print('decoded_access_token', decoded_access_token) user_id = decoded_access_token["sub"] collection_id = uuid.uuid4().hex new_collection = Collection(id=collection_id, name=collection_name, owner=user_id, is_public=False) print(new_collection) new_collection.insert() return jsonify({ "code": 200, "data": { "id": collection_id, "name": collection_name } })
def validate_token(access_token, issuer, audience, client_ids): # Client ID's list cid_list = [] if not isinstance(client_ids, list): cid_list = client_ids.split(',') else: cid_list = client_ids check_presence_of(access_token, issuer, audience, cid_list) # Decoding Header & Payload from token header = jwt.get_unverified_header(access_token) payload = jwt.get_unverified_claims(access_token) # Verifying Claims verify_claims(payload, issuer, audience, cid_list) # Verifying Signature jwks_key = fetch_jwk_for(header, payload) key = jwk.construct(jwks_key) message, encoded_sig = access_token.rsplit('.', 1) decoded_sig = base64url_decode(encoded_sig.encode('utf-8')) valid = key.verify(message.encode(), decoded_sig) # If the token is valid, it returns the payload if valid == True: return payload else: raise Exception('Invalid Token')
def get_username_from_token(self, token): if self.keys is None: (self.keys, self.keys_iss) = self.__get_userpool_keys() try: headers = jwt.get_unverified_header(token) except: return None if not headers.get('kid'): return None kid = headers['kid'] key_index = -1 for i in range(len(self.keys)): if kid == self.keys[i]['kid']: key_index = i break if key_index == -1: return None public_key = jwk.construct(self.keys[key_index]) message, encoded_signature = str(token).rsplit('.', 1) decoded_signature = base64url_decode(encoded_signature.encode('utf-8')) if not public_key.verify(message.encode("utf8"), decoded_signature): return None claims = jwt.get_unverified_claims(token) return claims["username"]
def login(org_slug=None): next_path = request.args.get('next') if not settings.REMOTE_JWT_LOGIN_ENABLED: logger.error( "Cannot use remote user for login without being enabled in settings" ) return redirect( url_for('redash.index', next=next_path, org_slug=org_slug)) jwttoken = request.headers.get( settings.REMOTE_USER_HEADER) or request.cookies.get('jwt') # Some Apache auth configurations will, stupidly, set (null) instead of a # falsey value. Special case that here so it Just Works for more installs. # '(null)' should never really be a value that anyone wants to legitimately # use as a redash user jwt. if jwttoken == '(null)': jwttoken = None if not jwt: logger.error( "Cannot use remote jwt for login when it's not provided in the request (looked in headers['" + settings.REMOTE_USER_HEADER + "'])") return redirect( url_for('redash.index', next=next_path, org_slug=org_slug)) try: public_key = get_jwt_public_key() jwt_decoded = jwt.get_unverified_claims( jwttoken) if public_key is '' else jwt.decode( jwttoken, public_key) email = jwt_decoded.get('email', None) if not email: logger.error( "Cannot use remote jwt for login when it's not provided in the request (looked in headers['" + settings.REMOTE_USER_HEADER + "'])") return redirect( url_for('redash.index', next=next_path, org_slug=org_slug)) logger.info("Logging in " + email + " via remote jwt") user = create_and_login_user(current_org, email, email) if user is None: return logout_and_redirect_to_index() resp = redirect(next_path or url_for('redash.index', org_slug=org_slug), code=302) resp.set_cookie('jwt', jwttoken, secure=True, httponly=True) return resp except jwt.JWTError, jwt.ExpiredSignatureError: logger.error( "Remote user attempted entry using key with invalid signature") logger.info(settings.REMOTE_JWT_EXPIRED_ENDPOINT) return redirect( url_for('redash.index', next=next_path, org_slug=org_slug))
def _get_claim_from_token(token: str, tgt: str): unverified_claims = jwt.get_unverified_claims(token) claim = unverified_claims.get(tgt) if claim is None: raise Unauthorized(description=f"Access denied: No {tgt}.") return claim
def verify_token_scopes(access_token: str, required_scopes: List[str]): claims = jwt.get_unverified_claims(access_token) token_scopes = claims["scope"].split() if not all(required_scope in token_scopes for required_scope in required_scopes): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Client does not have access to this operation", )
def get_issuer(token: str) -> str: """ Gets the issuer (iss) from the encoded token. :param token: the encoded token. :return: the issuer (iss) from the encoded token. """ decode = jwt.get_unverified_claims(token) return decode['iss'] if 'iss' in decode else None
def verify_jwt(token): try: claims = jwt.get_unverified_claims(token) data = jwt.decode(token, SECRET_KEY) except Exception as e: print(e) return False return claims == data
def handle_expired_signature(token, err): """Handles tokens with expired signatures.""" msg = 'Token provided by {} has expired'.format( jwt.get_unverified_claims(token).get('sub', 'sub not found')) current_app.logger.info(msg) raise JsonApiException(detail='{0}'.format(err), title='token expired', status=401)
def is_admin(request): try : token = get_token_auth_header(request) claims = jwt.get_unverified_claims(token) # TODO : move deploy/dev url to settings return 'admin' in claims['https://localhost:8000/api/roles'] except AttributeError: return request.user.is_superuser
def mock_cloud(hass, config={}): """Mock cloud.""" with patch('hass_nabucasa.Cloud.start', return_value=mock_coro()): assert hass.loop.run_until_complete(async_setup_component( hass, cloud.DOMAIN, { 'cloud': config })) hass.data[cloud.DOMAIN]._decode_claims = \ lambda token: jwt.get_unverified_claims(token)
def cloud_client(hass, test_client): """Fixture that can fetch from the cloud client.""" with patch('homeassistant.components.cloud.Cloud.async_start', return_value=mock_coro()): hass.loop.run_until_complete(async_setup_component(hass, 'cloud', { 'cloud': { 'mode': 'development', 'cognito_client_id': 'cognito_client_id', 'user_pool_id': 'user_pool_id', 'region': 'region', 'relayer': 'relayer', } })) hass.data['cloud']._decode_claims = \ lambda token: jwt.get_unverified_claims(token) with patch('homeassistant.components.cloud.Cloud.write_user_info'): yield hass.loop.run_until_complete(test_client(hass.http.app))
def fromJWT(self, token, publicKey, needOrgID, algorithm="HS256", really_dont_verify_tokens=False): """ Decode a JWT into a credential. You must know the orgID for which the cred should have been issued, because we need to verify that it matches. Returns a DataWireResult with a cred member on success. """ cred = None claims = None errorMessage = None try: if not publicKey: if not really_dont_verify_tokens: errorMessage = "public key is required to decode JWT" else: header = jwt.get_unverified_headers(token) if ("typ" not in header) or (header["typ"] != "JWT"): errorMessage = "malformed token (not a JWT)" elif ("alg" not in header) or (header["alg"] != "HS256"): errorMessage = "malformed token (not HS256)" else: claims = jwt.get_unverified_claims(token) else: claims = jwt.decode( token, publicKey, algorithms=algorithm, audience=needOrgID, issuer="cloud-hub.datawire.io" ) except JWSError as error: errorMessage = error.message if claims: rc = DataWireCredential.fromClaims(claims, needOrgID) if rc: cred = rc.cred else: errorMessage = rc.error return DataWireResult.fromErrorAndResults(error=errorMessage, cred=cred)
def get_active_jwt(self, jwt=None, session=None): """ Will fetch a new jwt if current jwt is expired """ if not jwt and not session: raise RuntimeError("Either jwt or session needs to be set") if session: jwt = session.get('jwt') jwt_data = jose_jwt.get_unverified_claims(jwt) jwt_data = json.loads(jwt_data) exp_date = datetime.datetime.fromtimestamp(jwt_data["exp"]) now = datetime.datetime.now() if now > exp_date: url = 'https://itsyou.online/v1/oauth/jwt/refresh' headers = {'Authorization': 'bearer {0}'.format(jwt)} resp = requests.get(url, headers=headers) jwt = "" if resp.status_code == 200: jwt = resp.content if session: session['jwt'] = jwt session.save() return jwt
def _decode_claims(self, token): # pylint: disable=no-self-use """Decode the claims in a token.""" from jose import jwt return jwt.get_unverified_claims(token)
def test_unverified_claims_object(self, claims, key): token = jwt.encode(claims, key) assert jwt.get_unverified_claims(token) == claims
def test_unverified_claims_list(self): token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.WyJpbnZhbGlkIiwgImNsYWltcyJd.nZvw_Rt1FfUPb5OiVbrSYZGtWSE5c-gdJ6nQnTTBkYo' with pytest.raises(JWTError): jwt.get_unverified_claims(token)
def test_unverified_claims_string(self): token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.aW52YWxpZCBjbGFpbQ.iOJ5SiNfaNO_pa2J4Umtb3b3zmk5C18-mhTCVNsjnck' with pytest.raises(JWTError): jwt.get_unverified_claims(token)
def test_bad_claims(self): bad_token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.iOJ5SiNfaNO_pa2J4Umtb3b3zmk5C18-mhTCVNsjnck' with pytest.raises(JWTError): jwt.get_unverified_claims(bad_token)
def check_auth(): """Determines if the Access Token is valid """ domain_base = "https://" + AUTH0_DOMAIN + "/" token = get_token_auth_header() if token in auth0_cache: return auth0_cache[token] # check token validity jsonurl = urlopen(domain_base + ".well-known/jwks.json") jwks = json.loads(jsonurl.read()) try: unverified_header = jwt.get_unverified_header(token) except JWTError: raise AuthError({"code": "improper_token", "description": "Token cannot be validated"}, 403) rsa_key = {} for key in jwks["keys"]: if key["kid"] == unverified_header["kid"]: rsa_key = { "kty": key["kty"], "kid": key["kid"], "use": key["use"], "n": key["n"], "e": key["e"] } break else: raise AuthError({"code": "invalid_header", "description": "Unable to find appropriate key"}, 403) try: payload = jwt.decode( token, rsa_key, algorithms=AUTH0_ALGORITHMS, audience=AUTH0_API_AUDIENCE, issuer=domain_base ) except jwt.ExpiredSignatureError: raise AuthError({"code": "token_expired", "description": "Token is expired"}, 403) except jwt.JWTClaimsError: raise AuthError({"code": "invalid_claims", "description": "Incorrect claims," "please check the audience and issuer"}, 403) except Exception: raise AuthError({"code": "invalid_header", "description": "Unable to parse authentication" " token."}, 403) # check scope unverified_claims = jwt.get_unverified_claims(token) if unverified_claims.get("scope"): token_scopes = unverified_claims["scope"].split() for token_scope in token_scopes: if token_scope == AUTH0_REQUIRED_SCOPE: _request_ctx_stack.top.current_user = payload auth0_cache[token] = True return True raise AuthError({"code": "access_denied", "description": "Access not allowed"}, 403)