async def _test_manager(): mock.setup_app_manager() # check manager role view_callable = asyncio.coroutine(get_user) info = await view_callable(mock.app) assert info.status == 200 info_decoded = jwt.decode(info.body, secret) assert info_decoded['result']['roles'] == {'site administrator': 1} # check manager can assign roles mock.params['scope'] = mock.scope mock.params['user'] = mock.new_user mock.params['roles'] = ['Editor'] mock.app = mock.app._replace(post=payload(mock.params), headers=mock.headers) view_callable = asyncio.coroutine(grant_user_scope_roles) info = await view_callable(mock.app) assert info.status in (200, 400) info_decoded = jwt.decode(info.body, secret) assert info_decoded['result'] in ('success', 'attributeOrValueExists') # check manager can get user and check added roles mock.params['user'] = mock.new_user mock.app = mock.app._replace(post=payload(mock.params), headers=mock.headers) view_callable = asyncio.coroutine(get_user) info = await view_callable(mock.app) assert info.status == 200 info_decoded = jwt.decode(info.body, secret) assert info_decoded['result']['roles'] == {'Editor': 1}
async def _test_add_scope(): #add scope by superadmin mock.setup_app_superuser() mock.params['scope'] = 'nou_test' mock.params['admin_user'] = '******' mock.app = mock.app._replace(post=payload(mock.params), headers=mock.headers) view_callable = asyncio.coroutine(add_scope) info = await view_callable(mock.app) assert info.status in (200, 400) info_decoded = jwt.decode(info.body, secret) assert info_decoded['result'] in ('success', 'entryAlreadyExists') #add already added scope mock.params['scope'] = 'nou_test' mock.params['admin_user'] = '******' mock.app = mock.app._replace(post=payload(mock.params), headers=mock.headers) view_callable = asyncio.coroutine(add_scope) info = await view_callable(mock.app) assert info.status == 400 info_decoded = jwt.decode(info.body, secret) assert info_decoded['result'] == 'entryAlreadyExists' #add scope by not superadmin mock.setup_app_user() mock.params['scope'] = 'nou_test_2' mock.params['admin_user'] = '******' mock.app = mock.app._replace(post=payload(mock.params), headers=mock.headers) view_callable = asyncio.coroutine(add_scope) with unittest.TestCase().assertRaises( HTTPBadRequest, msg = 'NOT VALID token: must be superuser'): info = await view_callable(mock.app)
def prepare(self): """Check if JWT or API key is provided and valid.""" if self.request.method == 'OPTIONS': return api_key = self.get_argument('api_key', default=None) or self.request.headers.get('X-Api-Key') if api_key and api_key == app.API_KEY: return authorization = self.request.headers.get('Authorization') if not authorization: return self._unauthorized('No authorization token.') if authorization.startswith('Bearer'): try: token = authorization.replace('Bearer ', '') jwt.decode(token, app.ENCRYPTION_SECRET, algorithms=['HS256']) except jwt.ExpiredSignatureError: return self._unauthorized('Token has expired.') except jwt.DecodeError: return self._unauthorized('Invalid token.') elif authorization.startswith('Basic'): auth_decoded = base64.decodestring(authorization[6:]) username, password = auth_decoded.split(':', 2) if username != app.WEB_USERNAME or password != app.WEB_PASSWORD: return self._unauthorized('Invalid user/pass.') else: return self._unauthorized('Invalid token.')
def before_request(): if request.endpoint == 'api.api_languages' or \ request.endpoint == 'api.api_corpus': return # check if we have a token token = request.args.get('token', '', type=str) access_granted = False if token == '': if 'X-Mashape-Proxy-Secret' in request.headers and \ request.headers['X-Mashape-Proxy-Secret'] == \ current_app.config['MASHAPE_SECRET']: access_granted = True elif 'X-Poio-Android-IPL' in request.headers and \ request.headers['X-Poio-Android-IPL'] == \ current_app.config['IPL_SECRET']: access_granted = True else: try: jwt.decode(token, current_app.config['SECRET_KEY']) access_granted = True except (jwt.DecodeError, jwt.ExpiredSignature): pass # return if not access_granted: return Response(json.dumps({'error': 'You do not have the rights to access the API.'}), mimetype='application/json')
def authenticate(self, handler, token): """ Authenticate with the JWT token that i've received Return None in case of """ try: self.log.info("I got the following data: " + str(token)) print('Secret: ' + str(self.secret_key)) if self.audience: decoded_token = jwt.decode(token, self.secret_key, options={'verify_iat': False}, audience=self.audience) else: decoded_token = jwt.decode(token, self.secret_key, options={'verify_iat': False, 'verify_aud': False}) if self.token_service_url: try: r = requests.post(self.token_service_url, headers={'Content-Type': 'application/json'}, data=json.dumps({'token': token})) if not r.ok: self.log.error(str(r.content)) else: self.log.info('Updated token service for user: '******'sub'])) except Exception as e: self.log.error('Error refreshing token in service ' + str(e)) return decoded_token['sub'] except Exception as e: self.log.error("Error parsing jwt token: " + str(e)) return
def test_officeconnector_reauth_does_not_checkout(self, browser): api.portal.set_registry_record( 'direct_checkout_and_edit_enabled', True, interface=IOfficeConnectorSettings) transaction.commit() # We cannot freeze time due to the test browser being threaded oc_url = create_oc_url( self.doc1.REQUEST, self.doc1, {'action': 'checkout'}) decoded_oc_url = jwt.decode(oc_url.split(':')[-1], verify=False) redirector_js = browser.login().open( self.doc1, view='checkout_documents' '?_authenticator={}&mode=external&reauth=1' .format(createToken()), ).css('script.redirector')[0].text tokens_from_js = [token for token in redirector_js.split("\'") if 'oc:' in token] self.assertEqual(3, len(tokens_from_js)) parsed_oc_url = tokens_from_js[0] decoded_parsed_oc_url = jwt.decode( parsed_oc_url.split(':')[-1], verify=False) # Take out the timestamps del decoded_oc_url['exp'] del decoded_parsed_oc_url['exp'] self.assertEqual(decoded_oc_url, decoded_parsed_oc_url) self.assertFalse(self.get_manager(self.doc1).is_checked_out_by_current_user())
def validate_jwt(request): logger.debug("Validating JWT") jwt_to_validate = request.POST.get('jwt', '') # Check that we actually have a token. if jwt_to_validate is not None: # Attempt to validate the JWT (Checks both expiry and signature) try: jwt.decode(jwt_to_validate, base64.b64decode(settings.AUTH0_SECRET, '-_'), algorithms=['HS256'], leeway=120, audience=settings.AUTH0_CLIENT_ID) response_data = {"status": "VALID"} except jwt.InvalidTokenError: logger.error("JWT token is invalid") response_data = {"stauts": "INVALID"} except jwt.ExpiredSignatureError: logger.error("JWT token expired") response_data = {"status": "EXPIRED_SIGNATURE"} else: logger.error("JWT token is missing") response_data = {"status": "NO_JWT"} return JsonResponse(response_data)
def require_auth(handler, kwargs): auth = handler.request.headers.get('Authorization') if auth: parts = auth.split() if parts[0].lower() != 'bearer': handler._transforms = [] handler.set_status(401) handler.write("invalid header authorization") handler.finish() elif len(parts) == 1: handler._transforms = [] handler.set_status(401) handler.write("invalid header authorization") handler.finish() elif len(parts) > 2: handler._transforms = [] handler.set_status(401) handler.write("invalid header authorization") handler.finish() token = parts[1] try: jwt.decode( token, secret_key, options=options ) except Exception, e: handler._transforms = [] handler.set_status(401) handler.write(e.message) handler.finish()
def test_encode_decode_with_rsa_sha384(self): # PEM-formatted RSA key with open('tests/testkey_rsa', 'r') as rsa_priv_file: priv_rsakey = load_pem_private_key(ensure_bytes(rsa_priv_file.read()), password=None, backend=default_backend()) jwt_message = jwt.encode(self.payload, priv_rsakey, algorithm='RS384') with open('tests/testkey_rsa.pub', 'r') as rsa_pub_file: pub_rsakey = load_ssh_public_key(ensure_bytes(rsa_pub_file.read()), backend=default_backend()) assert jwt.decode(jwt_message, pub_rsakey) # string-formatted key with open('tests/testkey_rsa', 'r') as rsa_priv_file: priv_rsakey = rsa_priv_file.read() jwt_message = jwt.encode(self.payload, priv_rsakey, algorithm='RS384') with open('tests/testkey_rsa.pub', 'r') as rsa_pub_file: pub_rsakey = rsa_pub_file.read() assert jwt.decode(jwt_message, pub_rsakey) load_output = jwt.load(jwt_message) jwt.verify_signature(key=pub_rsakey, *load_output)
def get_integration_from_token(token): """ When we create a jira server integration we create a webhook that contains a JWT in the URL. We use that JWT to locate the matching sentry integration later as Jira doesn't have any additional fields we can embed information in. """ if not token: raise ValueError('Token was empty') try: unvalidated = jwt.decode(token, verify=False) except jwt.DecodeError: raise ValueError('Could not decode JWT token') if 'id' not in unvalidated: raise ValueError('Token did not contain `id`') try: integration = Integration.objects.get( provider='jira_server', external_id=unvalidated['id']) except Integration.DoesNotExist: raise ValueError('Could not find integration for token') try: jwt.decode(token, integration.metadata['webhook_secret']) except Exception as err: raise ValueError('Could not validate JWT. Got %s' % err) return integration
def test_rsa_encode(self): root = os.path.dirname(__file__) pubkey = jwt.rsa_load_pub(os.path.join(root, "rsapubkey.pem")) jwt.decode( b"eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.cC4hiUPoj9Eetdgtv3hF80EGrhuB__dzERat0XF9g2VtQgr9PJbu3XOiZj5RZmh7AAuHIm4Bh-0Qc_lF5YKt_O8W2Fp5jujGbds9uJdbF9CUAr7t1dnZcAcQjbKBYNX4BAynRFdiuB--f_nZLgrnbyTyWzO75vRK5h6xBArLIARNPvkSjtQBMHlb1L07Qe7K0GarZRmB_eSN9383LcOLn6_dO--xi12jzDwusC-eOkHWEsqtFZESc6BfI7noOPqvhJ1phCnvWh6IeYI2w9QOYEUipUTI8np6LbgGY9Fs98rqVt5AXLIhWkWywlVmtVrBp0igcN_IoypGlUPQGe77Rw", pubkey, ) key = jwt.rsa_load(os.path.join(root, "rsakey.pem")) # Example from the JWS spec assert jwt.check( b"eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.cC4hiUPoj9Eetdgtv3hF80EGrhuB__dzERat0XF9g2VtQgr9PJbu3XOiZj5RZmh7AAuHIm4Bh-0Qc_lF5YKt_O8W2Fp5jujGbds9uJdbF9CUAr7t1dnZcAcQjbKBYNX4BAynRFdiuB--f_nZLgrnbyTyWzO75vRK5h6xBArLIARNPvkSjtQBMHlb1L07Qe7K0GarZRmB_eSN9383LcOLn6_dO--xi12jzDwusC-eOkHWEsqtFZESc6BfI7noOPqvhJ1phCnvWh6IeYI2w9QOYEUipUTI8np6LbgGY9Fs98rqVt5AXLIhWkWywlVmtVrBp0igcN_IoypGlUPQGe77Rw", key, ) assert not jwt.check( b"eyJhbGciOiJSUzI1NiJ9.AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.cC4hiUPoj9Eetdgtv3hF80EGrhuB__dzERat0XF9g2VtQgr9PJbu3XOiZj5RZmh7AAuHIm4Bh-0Qc_lF5YKt_O8W2Fp5jujGbds9uJdbF9CUAr7t1dnZcAcQjbKBYNX4BAynRFdiuB--f_nZLgrnbyTyWzO75vRK5h6xBArLIARNPvkSjtQBMHlb1L07Qe7K0GarZRmB_eSN9383LcOLn6_dO--xi12jzDwusC-eOkHWEsqtFZESc6BfI7noOPqvhJ1phCnvWh6IeYI2w9QOYEUipUTI8np6LbgGY9Fs98rqVt5AXLIhWkWywlVmtVrBp0igcN_IoypGlUPQGe77Rw", key, ) # XXX Should test the Signer classes directly. The check(encode()) dance # doesn't really verify that the correct algorithm was used, or that the # algorithm was implemented properly. assert jwt.check(jwt.encode(u"test", key, u"RS256"), key) assert jwt.check(jwt.encode(u"test", key, u"RS384"), key) assert jwt.check(jwt.encode(u"test", key, u"RS512"), key)
def validate_bearer_token(self, token, scopes, request): if token is None: return False try: payload = jwt.decode(token, verify=False) except jwt.InvalidTokenError: return False aud = request.host_url iss = payload['iss'] sub = payload.get('sub') client = get_client(request, iss) if client is None: return False try: payload = jwt.decode(token, key=client.client_secret, audience=aud, leeway=LEEWAY, algorithms=['HS256']) except jwt.InvalidTokenError: return False request.client = client request.user = sub return True
def verify_webpay_jwt(signed_jwt): # This can probably be deleted depending upon solitude. try: jwt.decode(signed_jwt.encode('ascii'), secret) except Exception, e: log.error('Error decoding webpay jwt: %s' % e, exc_info=True) return {'valid': False}
def wrapper(request, *args, **kw): raw_sig_request = request.GET.get('r') or request.POST.get('r') if not raw_sig_request: return http.HttpResponseBadRequest('r was not in request') raw_sig_request = str(raw_sig_request) allowed = False try: sig_request = jwt.decode(raw_sig_request, verify=False) except jwt.DecodeError: log.exception('signed request was invalid') else: user_email = sig_request['iss'] em = get_object_or_404(VerifiedEmail, email=user_email) if em.upload_key: try: jwt.decode(raw_sig_request, em.upload_key, verify=True) allowed = True except jwt.DecodeError: log.exception('signed request for %s was invalid' % user_email) else: log.info('no upload_key for %s' % user_email) if not allowed: return http.HttpResponseForbidden() return view(request, raw_sig_request, sig_request, *args, **kw)
def _is_valid(self): """Helper method that checks if token is valid. If token is generated for API key, the API key has to exist and be enabled. Otherwise, the token is generated for account. For both cases, we check that token didn't expire and that we can decode it using our client secret and HS256 algorithm. :rtype: bool :returns: True if token is valid, False otherwise """ if self.for_api_key: valid = self.api_key and self.api_key.is_enabled() else: valid = bool(self.account) if valid and \ datetime.datetime.utcnow() < \ datetime.datetime.utcfromtimestamp(float(self.exp)): try: jwt.decode( self.token, self.app._client.auth.secret, algorithms=['HS256'], leeway=LEEWAY) except jwt.DecodeError: return False return True return False
def get(self, request): # Check if file exists # print "GET: SIZE" response = HttpResponse() print request.GET['file'] upload_id = request.GET.get('uid') token = request.GET.get('token') try: print jwt.decode(token, SECRET_KEY) except: return Response('Authentication expired', status=401) print upload_id if upload_id != '': # queryset = MyChunkedUpload.objects.all() # chunked_uploaded = queryset.filter(upload_id=upload_id) chunked_uploaded = get_object_or_404(MyChunkedUpload, upload_id=upload_id) print chunked_uploaded try: print chunked_uploaded.file print type(chunked_uploaded.file) print chunked_uploaded.file.open size = chunked_uploaded.file.size print 'SIZE is: ' + str(size) return Response({'size': size}, status=200) except IOError: return Response({'size': 0}, status=200) else: return Response({'size': 0}, status=200)
def get_integration_from_jwt(token, path, query_params, method='GET'): # https://developer.atlassian.com/static/connect/docs/latest/concepts/authentication.html # Extract the JWT token from the request's jwt query # parameter or the authorization header. if token is None: raise AtlassianConnectValidationError('No token parameter') # Decode the JWT token, without verification. This gives # you a header JSON object, a claims JSON object, and a signature. decoded = jwt.decode(token, verify=False) # Extract the issuer ('iss') claim from the decoded, unverified # claims object. This is the clientKey for the tenant - an identifier # for the Atlassian application making the call issuer = decoded['iss'] # Look up the sharedSecret for the clientKey, as stored # by the add-on during the installation handshake try: integration = Integration.objects.get( provider='jira', external_id=issuer, ) except Integration.DoesNotExist: raise AtlassianConnectValidationError('No integration found') # Verify the signature with the sharedSecret and # the algorithm specified in the header's alg field. decoded_verified = jwt.decode(token, integration.metadata['shared_secret']) # Verify the query has not been tampered by Creating a Query Hash # and comparing it against the qsh claim on the verified token. qsh = get_query_hash(path, method, query_params) if qsh != decoded_verified['qsh']: raise AtlassianConnectValidationError('Query hash mismatch') return integration
def decode_token(self, token, use): kid = jwt.get_unverified_header(token).get('kid') jwt_set = [x for x in self.cognito_jwt_set.get('keys') if x.get('kid') == kid][0] n_str, e_str = jwt_set.get('n'), jwt_set.get('e') # signature verification included if use == 'access': decoded = jwt.decode(token, key=_public_key(n_str, e_str)) elif use == 'id': decoded = jwt.decode( token, key=_public_key(n_str, e_str), audience=app.config.get('COGNITO_CLIENT_ID')) else: raise exception.AuthError('unknown token_use:{}'.format(use)) if decoded.get('iss') != 'https://cognito-idp.{}.amazonaws.com/{}' \ .format(self.cognito_region, self.cognito_user_pool_id): raise exception.AuthError('token invalid. bad iss.') if decoded.get('token_use') != use: raise exception.AuthError( 'token invalid. bad token_use. expected {}'.format(use)) if datetime.datetime.fromtimestamp(decoded.get('exp'), pytz.utc) \ < datetime.datetime.now(pytz.utc): raise exception.AuthError('token invalid. expired.') return decoded
async def async_validate_access_token( self, token: str) -> Optional[models.RefreshToken]: """Return refresh token if an access token is valid.""" try: unverif_claims = jwt.decode(token, verify=False) except jwt.InvalidTokenError: return None refresh_token = await self.async_get_refresh_token( cast(str, unverif_claims.get('iss'))) if refresh_token is None: jwt_key = '' issuer = '' else: jwt_key = refresh_token.jwt_key issuer = refresh_token.id try: jwt.decode( token, jwt_key, leeway=10, issuer=issuer, algorithms=['HS256'] ) except jwt.InvalidTokenError: return None if refresh_token is None or not refresh_token.user.is_active: return None return refresh_token
def require_auth(handler, kwargs): auth = handler.request.headers.get('Authorization') if auth: parts = auth.split() if parts[0].lower() != 'bearer': handler._transforms = [] handler.writejson(json_decode(str(ApiHTTPError(10405)))) handler.finish() elif len(parts) == 1: handler._transforms = [] handler.writejson(json_decode(str(ApiHTTPError(10405)))) handler.finish() elif len(parts) > 2: handler._transforms = [] handler.writejson(json_decode(str(ApiHTTPError(10405)))) handler.finish() token = parts[1] try: jwt.decode( token, secret_key, options=options ) except Exception, e: handler._transforms = [] handler.set_status(200) handler.writejson({'message': e.message, 'code': 10416}) # handler.writejson(json_decode(str(ApiHTTPError(10403)))) handler.finish()
def req_ok(req): dd = jwt.decode(req['notice'], verify=False) eq_(dd['request'], payload['request']) eq_(dd['typ'], payload['typ']) jwt.decode(req['notice'], 'f', verify=True, audience=self.payment_issuer) return True
def test_encode_decode_with_rsa_sha512(self): try: from Crypto.PublicKey import RSA # PEM-formatted RSA key with open('tests/testkey_rsa', 'r') as rsa_priv_file: priv_rsakey = RSA.importKey(rsa_priv_file.read()) jwt_message = jwt.encode(self.payload, priv_rsakey, algorithm='RS512') with open('tests/testkey_rsa.pub', 'r') as rsa_pub_file: pub_rsakey = RSA.importKey(rsa_pub_file.read()) assert jwt.decode(jwt_message, pub_rsakey) load_output = jwt.load(jwt_message) jwt.verify_signature(key=pub_rsakey, *load_output) # string-formatted key with open('tests/testkey_rsa', 'r') as rsa_priv_file: priv_rsakey = rsa_priv_file.read() jwt_message = jwt.encode(self.payload, priv_rsakey, algorithm='RS512') with open('tests/testkey_rsa.pub', 'r') as rsa_pub_file: pub_rsakey = rsa_pub_file.read() assert jwt.decode(jwt_message, pub_rsakey) load_output = jwt.load(jwt_message) jwt.verify_signature(key=pub_rsakey, *load_output) except ImportError: pass
def test_encode_decode_with_ecdsa_sha512(self): try: import ecdsa # PEM-formatted EC key with open('tests/testkey_ec', 'r') as ec_priv_file: priv_eckey = ecdsa.SigningKey.from_pem(ec_priv_file.read()) jwt_message = jwt.encode(self.payload, priv_eckey, algorithm='ES512') with open('tests/testkey_ec.pub', 'r') as ec_pub_file: pub_eckey = ecdsa.VerifyingKey.from_pem(ec_pub_file.read()) assert jwt.decode(jwt_message, pub_eckey) load_output = jwt.load(jwt_message) jwt.verify_signature(key=pub_eckey, *load_output) # string-formatted key with open('tests/testkey_ec', 'r') as ec_priv_file: priv_eckey = ec_priv_file.read() jwt_message = jwt.encode(self.payload, priv_eckey, algorithm='ES512') with open('tests/testkey_ec.pub', 'r') as ec_pub_file: pub_eckey = ec_pub_file.read() assert jwt.decode(jwt_message, pub_eckey) load_output = jwt.load(jwt_message) jwt.verify_signature(key=pub_eckey, *load_output) except ImportError: pass
def test_no_secret(self): right_secret = "foo" bad_secret = "bar" jwt_message = jwt.encode(self.payload, right_secret) with self.assertRaises(jwt.DecodeError): jwt.decode(jwt_message)
def test_encode_decode_with_ecdsa_sha512(self): # PEM-formatted EC key with open('tests/testkey_ec', 'r') as ec_priv_file: priv_eckey = load_pem_private_key(ensure_bytes(ec_priv_file.read()), password=None, backend=default_backend()) jwt_message = jwt.encode(self.payload, priv_eckey, algorithm='ES512') with open('tests/testkey_ec.pub', 'r') as ec_pub_file: pub_eckey = load_pem_public_key(ensure_bytes(ec_pub_file.read()), backend=default_backend()) assert jwt.decode(jwt_message, pub_eckey) load_output = jwt.load(jwt_message) jwt.verify_signature(key=pub_eckey, *load_output) # string-formatted key with open('tests/testkey_ec', 'r') as ec_priv_file: priv_eckey = ec_priv_file.read() jwt_message = jwt.encode(self.payload, priv_eckey, algorithm='ES512') with open('tests/testkey_ec.pub', 'r') as ec_pub_file: pub_eckey = ec_pub_file.read() assert jwt.decode(jwt_message, pub_eckey) load_output = jwt.load(jwt_message) jwt.verify_signature(key=pub_eckey, *load_output)
def _verify(self, key, audience): if self.expiry - self.not_before > self.MAX_LIFETIME: raise self._error('grant token lifetime is too long') try: jwt.decode(self._token, algorithms=['HS256'], audience=audience, key=key, leeway=self.LEEWAY) except jwt.DecodeError: raise self._error('grant token signature is invalid') except jwt.exceptions.InvalidAlgorithmError: raise self._error('grant token signature algorithm is invalid') except jwt.MissingRequiredClaimError as exc: if exc.claim == 'aud': raise self._missing_field_error('aud', 'audience') else: raise self._missing_field_error(exc.claim) except jwt.InvalidAudienceError: raise self._invalid_field_error('aud', 'audience') except jwt.ImmatureSignatureError: raise self._error('grant token is not yet valid') except jwt.ExpiredSignatureError: raise self._error('grant token is expired') except jwt.InvalidIssuedAtError: raise self._error('grant token issue time (iat) is in the future')
def from_jwt(self, content): try: key = jwt.decode(content, verify=False).get('jwt-encode-key', '') except jwt.DecodeError as err: raise self._error('Error decoding JWT', error=err) if not key: raise self._error('No JWT key') secret = settings.CLIENT_JWT_KEYS.get(key, '') if not secret: raise self._error('No JWT secret for that key') try: content = jwt.decode(content, secret, verify=True) except jwt.DecodeError as err: raise self._error('Error decoding JWT', err) # We don't need this key anymore, delete it so that solitude # doesn't trigger a warning on it. del content['jwt-encode-key'] # Store the key and secret on the serializer, so that we can # return the same data. Assuming it's always going to be the # same object. self.jwt_key = {'key': key, 'secret': secret} return content
def validate_id_token(id_token, client_id, jwks_url): """ Ensures that the token we receive is valid. :param id_token: :param client_id: :param jwks_url: :return: """ # fetch token public key header_data = fetch_token_header(id_token) # retrieve the key material as specified by the token header r = requests.get(jwks_url) for key in r.json()['keys']: if key['kid'] == header_data['kid']: secret = get_rsa_public_key(key['n'], key['e']) algo = header_data['alg'] break else: return dict(message='Key not found'), 401 # validate your token based on the key it was signed with try: jwt.decode(id_token, secret.decode('utf-8'), algorithms=[algo], audience=client_id) except jwt.DecodeError: return dict(message='Token is invalid'), 401 except jwt.ExpiredSignatureError: return dict(message='Token has expired'), 401 except jwt.InvalidTokenError: return dict(message='Token is invalid'), 401
def for_request(self, request, body=None): if body and 'oauth_client_id' in body: rv = Tenant.objects.get(pk=body['oauth_client_id']) if rv is not None: return rv, {} jwt_data = request.GET.get('signed_request') if not jwt_data: header = request.META.get('HTTP_AUTHORIZATION', '') jwt_data = header[4:] if header.startswith('JWT ') else None if not jwt_data: raise BadTenantError('Could not find JWT') try: oauth_id = jwt.decode(jwt_data, verify=False)['iss'] client = Tenant.objects.get(pk=oauth_id) if client is not None: data = jwt.decode(jwt_data, client.secret) return client, data except jwt.exceptions.DecodeError: pass raise BadTenantError('Could not find tenant')
def _verify(self, key, audience): if self.expiry - self.not_before > self.MAX_LIFETIME: raise InvalidGrantError("Grant token lifetime is too long.") try: jwt.decode( self._token, algorithms=["HS256"], audience=audience, key=key, leeway=self.LEEWAY, ) except TypeError: raise InvalidClientError("Client is invalid.") except jwt.DecodeError: raise InvalidGrantError("Invalid grant token signature.") except jwt.exceptions.InvalidAlgorithmError: raise InvalidGrantError("Invalid grant token signature algorithm.") except jwt.MissingRequiredClaimError as exc: if exc.claim == "aud": raise errors.MissingJWTGrantTokenClaimError("aud", "audience") else: raise errors.MissingJWTGrantTokenClaimError(exc.claim) except jwt.InvalidAudienceError: raise errors.InvalidJWTGrantTokenClaimError("aud", "audience") except jwt.ImmatureSignatureError: raise InvalidGrantError("Grant token is not yet valid.") except jwt.ExpiredSignatureError: raise InvalidGrantError("Grant token is expired.") except jwt.InvalidIssuedAtError: raise InvalidGrantError("Grant token issue time (iat) is in the future.")
def post(self, request): try: authToken = request.headers["auth"] payload = jwt.decode(authToken,"secret") role = payload['role'] if(role =='School' ): schoolinfo = Login.objects.get(email__exact = payload['email']) schoolid = schoolinfo.id timetable = TimeTable.objects.filter(schoolid__exact = schoolid, classid__exact = request.data["classid"], day__exact = request.data["day"], period__exact = request.data["period"]).get_or_create()[0] timetable.schoolid = schoolid timetable.classid = request.data["classid"] timetable.day = request.data["day"] timetable.period = request.data["period"] timetable.teacherid = request.data["teacherid"] timetable.subjectid = request.data["subjectid"] timetable.save() return Response(dict(code="200", message="Success"), status = status.HTTP_200_OK) return Response(dict(code="400", message="Unauthrized Access"), status= status.HTTP_401_UNAUTHORIZED) except jwt.exceptions.ExpiredSignatureError: return Response(dict(code="400", message="Expired Signature"), status= status.HTTP_401_UNAUTHORIZED) except jwt.exceptions.DecodeError: return Response(dict(code="400", message="Invalid Token"), status= status.HTTP_401_UNAUTHORIZED) except: return Response(dict(code="400", message="Something went wrong"), status= status.HTTP_401_UNAUTHORIZED)
def get_userid_from_jwttoken(request): """Extract user_id field from JWT Token Args: request (HTTP request): Flask HTTP request object Returns: [int]: User Identifier """ token = None if 'Authorization' in request.headers: auth_header = request.headers['Authorization'] if auth_header[0:7] == 'Bearer': token = auth_header[7:] else: token = auth_header if not token: return token try: token_data = jwt.decode(token, current_app.config['SECRET_KEY']) return token_data['user_id'] except: return None
def parse_insecure(cls, token: str, expected_audience: List[str]) -> 'JwtSvid': """Parses and validates a JWT-SVID token and returns an instance of a JwtSvid with a SPIFFE ID parsed from the 'sub', audience from 'aud', and expiry from 'exp' claim. The JWT-SVID signature is not verified. Args: token: A token as a string that is parsed and validated. expected_audience: Audience as a list of strings used to validate the 'aud' claim. Returns: An instance of JwtSvid with a SPIFFE ID parsed from the 'sub', audience from 'aud', and expiry from 'exp' claim. Raises: ArgumentError: When the token is blank or cannot be parsed, or in case header is not specified or in case expected_audience is empty or if the SPIFFE ID in the 'sub' claim doesn't comply with the SPIFFE standard. InvalidAlgorithmError: In case specified 'alg' is not supported as specified by the SPIFFE standard. InvalidTypeError: If 'typ' is present in header but is not set to 'JWT' or 'JOSE'. InvalidClaimError: If a required claim ('exp', 'aud', 'sub') is not present in payload or expected_audience is not a subset of audience_claim. TokenExpiredError: If token is expired. InvalidTokenError: If token is malformed and fails to decode. """ if not token: raise ArgumentError( INVALID_INPUT_ERROR.format('token cannot be empty')) try: header_params = jwt.get_unverified_header(token) validator = JwtSvidValidator() validator.validate_header(header_params) claims = jwt.decode(token, options={'verify_signature': False}) validator.validate_claims(claims, expected_audience) spiffe_id = SpiffeId.parse(claims['sub']) return JwtSvid(spiffe_id, claims['aud'], claims['exp'], claims, token) except PyJWTError as err: raise InvalidTokenError(str(err))
def verify_token(token): """ Verify authorization token :param token: :return: """ try: response = jwt.decode(token, current_app.config['PUBLIC_KEY'], audience='') u = User.objects.get(id=response['user']['id']) if u is None: return False else: g.client = u return True except Exception as ex: print(ex) return False
def decorated(*args, **kwargs): token = None transaction_id = transactionid_generator() logger.info('API - AUDIT - %s - Accessing %s %s', transaction_id, request.method, request.url) if 'x-access-token' in request.headers: token = request.headers['x-access-token'] if not token: logger.info('API - AUDIT - %s - Token is missing.', transaction_id) return jsonify({ 'transactionId': transaction_id, 'operationResult': 'TOKEN IS MISSING' }), 403 try: data = jwt.decode(token, app.config['SECRET_KEY']) current_user = User.query.filter_by( public_id=data['public_id']).first() if not current_user: logger.info('API - AUDIT - %s - User does not exist.', transaction_id) return jsonify({ 'transactionId': transaction_id, 'operationResult': 'INVALID USER CREDENTIALS' }), 403 except: logger.info('API - AUDIT - %s - Invalid token.', transaction_id) return jsonify({ 'transactionId': transaction_id, 'operationResult': 'INVALID TOKEN' }), 403 return func(current_user, transaction_id, *args, **kwargs)
def jwt_authorize_project(project, payload): """Authorize the project for the payload.""" try: if payload is None: return handle_error(INVALID_HEADER_MISSING) parts = payload.split() if parts[0].lower() != 'bearer': return handle_error(INVALID_HEADER_BEARER) elif len(parts) == 1: return handle_error(INVALID_HEADER_TOKEN) elif len(parts) > 2: return handle_error(INVALID_HEADER_BEARER_TOKEN) data = jwt.decode(parts[1], project.secret_key, 'H256') if (data['project_id'] == project.id and data['short_name'] == project.short_name): return True else: return handle_error(WRONG_PROJECT_SIGNATURE) except exceptions.DecodeError: return handle_error(DECODE_ERROR_SIGNATURE)
def authenticate(self, request): header = request.headers.get('Authentication') if not header: return None #this request is not authenticated if not header.startswith('Bearer'): raise AuthenticationFailed( {'message': 'Invalid Authorization header'}) token = header.replace('Bearer ', '') #get the token from the headers try: payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256']) user = User.objects.get(pk=payload.get('sub')) except jwt.exceptions.InvalidTokenError: raise AuthenticationFailed({'message': 'Invalid Token'}) except User.DoesNotExist: raise AuthenticationFailed({'message': 'Invalid Subject'}) return (user, token) #returns tuple
def parse(cls, token: str, key: str = None, verify: bool = True, algorithm: str = 'HS256') -> 'Jwt': try: json = jwt.decode(token, key=key or current_app.config['SECRET_KEY'], verify=verify, algorithms=algorithm, audience=current_app.config['OAUTH2_CLIENT_ID'] or request.url_root) except (DecodeError, ExpiredSignature, InvalidAudience): raise return Jwt( iss=json.get('iss', None), typ=json.get('typ', None), sub=json.get('sub', None), aud=json.get('aud', None), exp=json.get('exp', None), nbf=json.get('nbf', None), iat=json.get('iat', None), jti=json.get('jti', None), name=json.get('name', None), preferred_username=json.get('preferred_username', None), email=json.get('email', None), provider=json.get('provider', None), orgs=json.get('orgs', list()), groups=json.get('groups', list()), roles=json.get('roles', list()), scopes=json.get('scope', '').split( ' '), # eg. scope='read write' => scopes=['read', 'write'] email_verified=json.get('email_verified', None), customers=[json['customer']] if 'customer' in json else json.get( 'customers', list()))
def _verify_token(self, token, use): """ Verifies all aspects of the given *token* (a signed JWT) which is expected to be used for the given *use* (``id`` or ``access``). Assertions about expected algorithms, audience, issuer, and token use follow guidelines from <https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-verifying-a-jwt.html>. """ jwk = self.jwks.get_signing_key_from_jwt(token) try: claims = jwt.decode( token, jwk.key, algorithms=["RS256"], audience=self.client_id if use != "access" else None, issuer=self.user_pool_url, options={"require": ["exp"]}) except jwt.exceptions.ExpiredSignatureError: raise ExpiredTokenError(use) except jwt.exceptions.InvalidTokenError as e: raise TokenError(f"{type(e).__name__}: {str(e)}") claimed_use = claims.get("token_use") if claimed_use != use: raise InvalidUseError( f"{use} (expected) != {claimed_use} (claimed)") self._tokens[use] = token self._claims[use] = claims return claims
def post(self, request): try: authToken = request.headers["auth"] payload = jwt.decode(authToken,"secret") role = payload['role'] schoolid = '' if(role =='School'): schoolinfo = Login.objects.get(email__exact = payload["email"]) schoolid = schoolinfo.id userinfo = UserSerializer(Login.objects.get(id__exact = request.data["id"])) employeedata = EmployeeSerializer(Employee.objects.get(userid__exact = request.data["id"])) userinfo = userinfo.data employeedata = employeedata.data employeeclass = Class.objects.get(id__exact = employeedata["classid"]) employeedata["currentclass"] = employeeclass.classname classinfo = ClassSerializer(Class.objects.filter(schoolid__exact = schoolid).all(), many=True) return Response(dict(employeinfo = employeedata , userinfo = userinfo, classes = classinfo.data), status = status.HTTP_200_OK) return Response(dict(code="400", message="Unauthrized Access"), status= status.HTTP_401_UNAUTHORIZED) except jwt.exceptions.ExpiredSignatureError: return Response(dict(code="400", message="Expired Signature"), status= status.HTTP_401_UNAUTHORIZED) except jwt.exceptions.DecodeError: return Response(dict(code="400", message="Invalid Token"), status= status.HTTP_401_UNAUTHORIZED) except: return Response(dict(code="400", message="Something went wrong"), status= status.HTTP_401_UNAUTHORIZED)
def post(self, request): try: authToken = request.headers["auth"] payload = jwt.decode(authToken,"secret") role = payload['role'] if(role =='School'): excel_file = request.FILES["file"] wb = openpyxl.load_workbook(excel_file) worksheet = wb["Sheet1"] for row in worksheet.iter_rows(): link = row[1].value link = link.split("v=")[1] link = link.split("&")[0] link = "https://www.youtube.com/embed/"+link tutorial = EducationPortal(subjectid = request.data["subjectid"], chaptername=row[0].value, videolink=link) tutorial.save() return Response(dict(code="200", message="pass"), status = status.HTTP_200_OK) return Response(dict(code="400", message="Unauthrized Access"), status= status.HTTP_401_UNAUTHORIZED) except jwt.exceptions.ExpiredSignatureError: return Response(dict(code="400", message="Expired Signature"), status= status.HTTP_401_UNAUTHORIZED) except jwt.exceptions.DecodeError: return Response(dict(code="400", message="Invalid Token"), status= status.HTTP_401_UNAUTHORIZED) except: return Response(dict(code="400", message="Something went wrong"), status= status.HTTP_401_UNAUTHORIZED)
def post(self): p = request.form['data'] data = p.encode('utf8') data = jwt.decode(data, salt, algorithms=['HS256']) access_token = data['access_token'][0] user = check_token(access_token) if data['shared']: shared_camera = SharedCameras(camera_id=data['camera_id'], shared=data['shared']) shared_camera.save() print(data['shared_list']) if data['shared_list'] != []: for l in data['shared_list']: check_shared_camera = SharedCameras.objects( camera_id=data['camera_id'], shared=l).first() if check_shared_camera == None: shared_camera = SharedCameras(camera_id=data['camera_id'], shared=l) shared_camera.save() encoded_jwt = jwt.encode(data, salt, algorithm='HS256', headers={'message': 'OK'}) return {"test": encoded_jwt.decode("utf-8")}
def test_03_jwt_scope_claim(self): user = DjangoTestClient() user.login(username=USER_USERNAME, password=USER_PASSWORD) parameters = { "client_id": self.client_application.key, "scope": "first_name last_name", "redirect_uri": REDIRECT_URI, "response_type": "code" } response = user.get("/oauth2/authorize_first_and_last_name?%s" % urlencode(parameters)) qs = parse_qs(urlparse(response['location']).query) code = qs['code'] client = DjangoTestClient() parameters = { "client_id": self.client_application.key, "grant_type": "authorization_code", "code": code, "redirect_uri": REDIRECT_URI, "scope": "first_name last_name" } basic_auth = b64encode( "%s:%s" % (self.client_application.key, self.client_application.secret)) response = client.get("/oauth2/token", parameters, HTTP_AUTHORIZATION="Basic %s" % basic_auth) token = json.loads(response.content)["access_token"] jwt_payload = jwt.decode(token, settings.OAUTH2_JWT_KEY, algorithms=['HS256'], audience=settings.OAUTH2_JWT_AUDIENCE) self.assertEqual(jwt_payload['family_name'], self.user.last_name) self.assertEqual(jwt_payload['given_name'], self.user.first_name)
async def get_current_user(db=Depends(session.get_db), token: str = Depends(security.oauth2_scheme)): credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) try: payload = jwt.decode(token, security.SECRET_KEY, algorithms=[security.ALGORITHM]) email: Optional[str] = payload.get("sub") if email is None: raise credentials_exception permissions: Optional[str] = payload.get("permissions") if permissions is None: raise credentials_exception token_data = schemas.TokenData(email=email, permissions=permissions) except PyJWTError: raise credentials_exception user = get_user_by_email(db, str(token_data.email)) if user is None: raise credentials_exception return user
def _authenticate_credentials(self, request, token): """ We will try to authenticate the token. If authentication is successful we return (user, token), otherwise we return an `AuthenticationFailed` error. """ try: payload = jwt.decode(token, settings.SECRET_KEY) except jwt.ExpiredSignatureError: msg = 'Your token has expired, please log in again.' raise exceptions.AuthenticationFailed(msg) except Exception as e: msg = str(e) raise exceptions.AuthenticationFailed(msg) try: user = User.objects.get(pk=payload['id']) except User.DoesNotExist: msg = 'User matching this token was not found.' raise exceptions.AuthenticationFailed(msg) if not user.is_active: msg = 'Forbidden! This user has been deactivated.' raise exceptions.AuthenticationFailed(msg) # active_session = UserDevices.objects.filter(user_id=user.id).first() # if active_session == None: # print("No active session") # uDevice = UserDevices(user=user, token=token) # uDevice.save() # if active_session != None and active_session.token != token: # print("Active session already exists") # raise exceptions.AuthenticationFailed("User session is active on other device") return (user, token)
def get_token_data(token): """ checks validity of a token Args: token (str): token to be validated Return: user (obj): valid user object """ try: payload = jwt.decode( token, settings.SECRET_KEY, algorithms="HS256", ) user = User.objects.get(email=payload['email']) except Exception as error: exception_mapper = { jwt.ExpiredSignatureError: "Token expired. Please login to get a new token.", jwt.DecodeError: "Authorization failed due to an Invalid token.", } message = exception_mapper.get(type(error), 'Authorization failed.') raise exceptions.AuthenticationFailed(message) return user
def verify_jwt_token(token: str, bl_token_repo=None, leeway=0) -> TokenPayload: from bountydns.api import config # environment must be loaded if bl_token_repo: if bl_token_repo.exists(token=token): raise HTTPException(status_code=403, detail="Forbidden") else: logger.warning( "verifying token without checking the blacklist. dangerous!") try: payload = jwt.decode(token, config.API_SECRET_KEY, algorithms=config.JWT_ALGORITHM, leeway=leeway) except jwt.PyJWTError: raise HTTPException(status_code=403, detail="Forbidden") return TokenPayload( payload=payload, scopes=payload.get("scopes", "").split(" "), token=token, sub=payload.get("sub", ""), exp=payload.get("exp", ""), )
def extract_user(): token = request.headers.get('Authorization') if not token: raise MissingTokenError try: token = token.split(' ')[1] data = jwt.decode(token, os.environ['SECRET_KEY']) except (DecodeError, KeyError, IndexError): raise InvalidTokenError except ExpiredSignatureError: raise ExpiredTokenError session = get_session() try: current_user = session.query(User).filter_by( username=data['username']).one() except NoResultFound: raise InvalidTokenError return current_user
def login(self): """Authenticate with email and password to Eva Calor""" url = API_URL + API_PATH_LOGIN payload = {'email': self.email, 'password': self.password} payload = json.dumps(payload) extra_headers = {'local': 'true', 'Authorization': self.unique_id} headers = self._headers() headers.update(extra_headers) try: response = requests.post(url, data=payload, headers=headers, allow_redirects=False, timeout=DEFAULT_TIMEOUT_VALUE) except (requests.exceptions.ConnectionError, requests.exceptions.Timeout): raise ConnectionError( str.format("Connection to {0} not possible", url)) if response.status_code != 200: raise UnauthorizedError( 'Failed to login, please check credentials') res = response.json() self.token = res['token'] self.refresh_token = res['refresh_token'] claimset = jwt.decode(res['token'], verify=False) self.token_expires = claimset.get('exp') return True
def _decode_token_with_verify(token: str) -> dict: """ Decode a jwt token. :param token: The token to decode. :type token: str :return: A dict containing the payload """ unverified_header = {} try: unverified_header = jwt.get_unverified_header(token) except jwt.DecodeError: logger.exception('Error decoding the unverified_header') return {} kid = unverified_header.get("kid") if kid is None: logger.error(f'Token did not include a "kid" header') return {} public_key = get_jwks(kid) if not public_key: logger.error('Could not load requested public key from the JWKS') return {} aud = get_target_audience() try: return jwt.decode(token, public_key, audience=aud, algorithms=['RS256']) except (jwt.InvalidSignatureError, jwt.InvalidIssuedAtError, jwt.InvalidIssuerError, jwt.ExpiredSignatureError, jwt.InvalidAudienceError, jwt.DecodeError, TypeError): logger.exception('Error decoding the token') return {}
def app_main(): smart = _smart_client() print(session['state']) if app.user_practitioner is None: idtoken = session['state']['launch_context']['id_token'] if idtoken is None: return msg('id-token not found') jwtDecoded = jwt.decode(idtoken, verify=False) practitioner_id = jwtDecoded['fhirUser'].split('/')[1] app.user_practitioner = smart.user_practitioner(practitioner_id) return render_template( 'index.html', page='request', proclient=smart, observations=smart.getobservations(), requests=smart.getrequests(), questionnaires=smart.instrumentlist_questionnaires, promis=smart.instrumentlist_promis, activetasks=smart.instrumentlist_activetasks, activityinstruments=smart.instrumentList_activity, clinicalrecords=smart.instrumentlist_clinicalrecords, devices=smart.instrumentlist_devices)
def add_compute(): back = request.args.get('next') user = get_user() if user == 'error': return redirect(url_for('logout')) cameras = get_cameras() form = ComputeForm() choice = [] for c in cameras: choice.append((c['id'],c['group_name']+' '+c['name'])) form.cameras.choices = choice if form.validate_on_submit(): data = { "name":form.name.data, 'access_token': session['google_token'], "cameras":form.cameras.data } processors =jwt.encode( data, salt, algorithm='HS256', headers={'message': 'OK'}) r = requests.post("http://127.0.0.1:7000/api/processors", data={'data':processors.decode('utf8')}) r_data = json.loads(r.text)['test'].encode('utf8') processors = jwt.decode(r_data, salt, algorithms=['HS256']) flash('Group '+ form.name.data + ' added', 'green lighten-2') return redirect(back) return render_template('add_compute.html', title="Cameras", form=form, user=user, back=back)
def test_login_get_get_portfolio_wrong_link(self): login_res = self.client().post(f'{self.prefix}/members/login', json=dict(email=self.username1, password=self.password1)) self.access_token = json.loads(login_res.data)['access_token'] token = jwt.decode(self.access_token, self.app.config['SECRET_KEY'], algorithms=["HS256"]) self.user_id = token['uid'] self.headers.update({ 'Authorization': f'Bearer {self.access_token}', 'Accept': "application/json" }) self.assertEqual(200, login_res.status_code) json_obj = {"link": '12343fvfdbnthfbvfcd'} base = self.prefix + '/rebalance' res = self.client().post(base + '/rebalanced', headers=self.headers, json=json_obj) self.assertEqual(400, res.status_code)
def custom_request_handler(request): api_token = request.headers["api_token"] user_id = request.headers["user_id"] request.data = json.loads(request.data) raw = request.data.get("raw", "") if raw != "": input = jwt.decode(str(raw), api_token, algorithms=["HS512"]) sub = input.get("sub", None) # print("Conditional") if sub and type(sub) is dict: sub = json.dumps(sub) if sub: decoded = json.loads(sub) messaging = decoded.get("messaging", None) return { "api_token": api_token, "user_id": user_id, "messaging": messaging }
def wrapped_handler(*args, **kwargs): if os.environ.get("NO_AUTH",False): return handler(*args, **kwargs) if flask.request.headers.get("Authorization") is None: return flask.Response( response= json.dumps({"error": "Request Missing Authorization Header"}), status=403, content_type="application/json" ) encoded_token = flask.request.headers.get("Authorization") json_token = jwt.decode(encoded_token, KEY, algorithms='HS256',audience = 'https://fairscape.org') if json_token.get('role',None) == 'admin': return handler(*args, **kwargs) elif allowed_user(json_token): return handler(*args, **kwargs) else: return flask.Response( response=json.dumps({"error": "failed to authorize user"}), status=401, content_type="application/json" )
def decorated_function(*args, **kwargs): access_token = request.headers.get('Authorization') if access_token is not None: try: payload = jwt.decode(access_token, auth_app.config['JWT_SECRET_KEY'], 'HS256') if not payload['registered']: raise jwt.InvalidTokenError except jwt.InvalidTokenError: payload = None if payload is None: return Response(status=401) usr_email = payload['email'] g.usr_email = usr_email g.usr = find_user(email=usr_email) if usr_email else None else: return 'Managers Only' return f(*args, **kwargs)
def decorated (*args, **kwargs): token = None # jwt is passed in a cookie named x-access-token if (app.config.get('USE_AUTH_HEADER')==False): # explictly comparing with False is safer! token = request.cookies.get (TOKEN_ID) else: # jwt is passed in a request header named x-access-token token = request.headers.get (TOKEN_ID) if token is None: print ('Auth failed. Missing security token: {}'.format(TOKEN_ID)) return ({'result' : False, 'error' : 'missing security token'}, 401) try: # decode the payload to fetch the current user decoded_token = jwt.decode (token, app.config.get('SECRET_KEY')) print ('Decoded token: ', decoded_token) mail = decoded_token['email'] current_user = User.query.filter_by (email=mail).first() except Exception as e: print ('Exception: ', e) return ({'result' : False, 'error' : str(e)}, 401) if (current_user is None): # will not normally reach here, but the user may have got deleted after logging in return ({'result' : False, 'error' : 'invalid or expired token'}, 401) # returns the current user's context to the routes return f (current_user, *args, **kwargs)
def authenticate(self, request): auth_data = authentication.get_authorization_header(request) if not auth_data: return None prefix, token = auth_data.decode('utf-8').split(' ') try: payload = jwt.decode(token, settings.JWT_SECRET_KEY, algorithms=["HS256"]) user = User.objects.get(username=payload['username']) return (user, token) except jwt.DecodeError as identifier: raise exceptions.AuthenticationFailed( 'Your token is invalid,login') except jwt.ExpiredSignatureError as identifier: raise exceptions.AuthenticationFailed( 'Your token is expired,login') return super().authenticate(request)
def _auth_method_oauth2(self): if request.httprequest.method == 'GET': mode = 'read' if request.httprequest.method == 'POST': mode = 'write' token_data = request.httprequest.headers.get('Authorization') if not token_data: raise Unauthorized() token_authorization = token_data.split()[0] if token_authorization != 'Bearer': raise Unauthorized() access_token = token_data.split()[1] # Token validation options = { # not sure why, you might need to do that if token is not encrypted 'verify_signature': False, 'verify_aud': False } jwt_decoded = jwt.decode(access_token, options=options) # validation # is the iss = to Compassions IDP ? if jwt_decoded.get('iss') not in VALID_ISSUERS: raise Unauthorized() # is scope read or write in scopes ? scope = jwt_decoded.get('scope') if scope and mode not in scope: raise Unauthorized() client_id = jwt_decoded.get('client_id') or jwt_decoded.get('ClientID') logger.info("TOKEN CLIENT IS -----------------> " + client_id) user = request.env['res.users'].sudo().search([('login', '=', client_id)]) if user: request.uid = user.id else: raise Unauthorized()
def valid(self, cert, token_claim_type, both_token_claim=False): try: decryptedHeader = jwt.get_unverified_header(cert) kid = decryptedHeader['kid'] except: return None if kid not in self.cognito_keys: self.cognito_keys_update() if kid not in self.cognito_keys: return None jwk = self.cognito_keys[kid] n = decode_base64urlUInt(jwk['n']) e = decode_base64urlUInt(jwk['e']) secret = RSA.construct((n, e)).exportKey() try: decoded = jwt.decode(cert, secret, issuer=self.iss, audience=self.aud) except: return None claim = decoded['token_use'] if both_token_claim: if claim not in ['access', 'id']: return None else: if claim != token_claim_type: return None return decoded