def test_deterministic_headers(self): from collections import OrderedDict from jose.utils import base64url_decode claims = {"a": "b"} key = "secret" headers1 = OrderedDict(( ('kid', 'my-key-id'), ('another_key', 'another_value'), )) encoded1 = jwt.encode(claims, key, algorithm='HS256', headers=headers1) encoded_headers1 = encoded1.split('.', 1)[0] headers2 = OrderedDict(( ('another_key', 'another_value'), ('kid', 'my-key-id'), )) encoded2 = jwt.encode(claims, key, algorithm='HS256', headers=headers2) encoded_headers2 = encoded2.split('.', 1)[0] assert encoded_headers1 == encoded_headers2 # manually decode header to compare it to known good decoded_headers1 = base64url_decode(encoded_headers1.encode('utf-8')) assert decoded_headers1 == b"""{"alg":"HS256","another_key":"another_value","kid":"my-key-id","typ":"JWT"}"""
def test_require(self, claims, key, claim, value): options = {"require_" + claim: True, "verify_" + claim: False} token = jwt.encode(claims, key) with pytest.raises(JWTError): jwt.decode(token, key, options=options, audience=str(value)) new_claims = dict(claims) new_claims[claim] = value token = jwt.encode(new_claims, key) jwt.decode(token, key, options=options, audience=str(value))
def generate_jwt_token(info): secret = current_app.config['SECRET_KEY'] token_duration = current_app.config['TOKEN_SECONDS'] token_expires_on = now() + timedelta(seconds=int(token_duration)) payload = {'exp': token_expires_on} payload.update(info) return jwt.encode(payload, secret, algorithm='HS256')
async def test_login_view(hass, cloud_client, mock_cognito): """Test logging in.""" mock_cognito.id_token = jwt.encode({ 'email': '*****@*****.**', 'custom:sub-exp': '2018-01-03' }, 'test') mock_cognito.access_token = 'access_token' mock_cognito.refresh_token = 'refresh_token' with patch('hass_nabucasa.iot.CloudIoT.connect') as mock_connect, \ patch('hass_nabucasa.auth.CognitoAuth._authenticate', return_value=mock_cognito) as mock_auth: req = await cloud_client.post('/api/cloud/login', json={ 'email': 'my_username', 'password': '******' }) assert req.status == 200 result = await req.json() assert result == {'success': True} assert len(mock_connect.mock_calls) == 1 assert len(mock_auth.mock_calls) == 1 result_user, result_pass = mock_auth.mock_calls[0][1] assert result_user == 'my_username' assert result_pass == 'my_password'
def _mktoken(userid): exp = int(time.time()) + VALID_FOR_TIME_S verified = { "uid": userid, "exp": exp, } return jwt.encode(verified, JWT_SECRET, algorithm=JWT_ALGO), exp
async def test_websocket_subscription_no_reconnect_if_expired( hass, hass_ws_client, aioclient_mock, mock_auth): """Test querying the status and not reconnecting because still expired.""" aioclient_mock.get(SUBSCRIPTION_INFO_URL, json={'provider': 'stripe'}) hass.data[DOMAIN].id_token = jwt.encode({ 'email': '*****@*****.**', 'custom:sub-exp': '2018-01-03' }, 'test') client = await hass_ws_client(hass) with patch( 'homeassistant.components.cloud.auth_api.renew_access_token' ) as mock_renew, patch( 'homeassistant.components.cloud.iot.CloudIoT.connect' ) as mock_connect: await client.send_json({ 'id': 5, 'type': 'cloud/subscription' }) response = await client.receive_json() assert response['result'] == { 'provider': 'stripe' } assert len(mock_renew.mock_calls) == 1 assert len(mock_connect.mock_calls) == 1
def test_login_view(hass, cloud_client, mock_cognito): """Test logging in.""" mock_cognito.id_token = jwt.encode({ 'email': '*****@*****.**', 'custom:sub-exp': '2018-01-03' }, 'test') mock_cognito.access_token = 'access_token' mock_cognito.refresh_token = 'refresh_token' with patch('homeassistant.components.cloud.iot.CloudIoT.' 'connect') as mock_connect, \ patch('homeassistant.components.cloud.auth_api._authenticate', return_value=mock_cognito) as mock_auth: req = yield from cloud_client.post('/api/cloud/login', json={ 'email': 'my_username', 'password': '******' }) assert req.status == 200 result = yield from req.json() assert result['email'] == '*****@*****.**' assert result['sub_exp'] == '2018-01-03' assert len(mock_connect.mock_calls) == 1 assert len(mock_auth.mock_calls) == 1 cloud, result_user, result_pass = mock_auth.mock_calls[0][1] assert result_user == 'my_username' assert result_pass == 'my_password'
def test_non_default_headers(self, claims, key, headers): encoded = jwt.encode(claims, key, headers=headers) decoded = jwt.decode(encoded, key) assert claims == decoded all_headers = jwt.get_unverified_headers(encoded) for k, v in headers.items(): assert all_headers[k] == v
async def test_unauthorized_is_raised_for_invalid_type(testapp): token = jwt.encode({'user': '******'}, 'SWORDFISH') resp = await testapp.get('/', headers={ 'Authorization': 'token ' + token }) assert resp.status == 401 assert 'Unsupported auth type' in await resp.text()
async def test_authentication_succeeds(testapp): token = jwt.encode({'user': '******'}, 'SWORDFISH') resp = await testapp.get('/success', headers={ 'Authorization': 'bearer ' + token }) async with resp: assert resp.status == 200
def generate_JWT(User,Privilage): tmp_claims = claims() time = datetime.utcnow() tmp_claims['iat']=time tmp_claims['exp']=time+timedelta(hours=1) #one hour tmp_claims['user']=User tmp_claims['privilage']=Privilage encoded = jwt.encode(tmp_claims, key(), algorithm='HS384') return encoded
def POST(self): s = web.input(user=None, password=None) if db.verifyUser(s.user, s.password): token = jwt.encode({'user': s.user, 'logedin': 'true'}, hc.JWT_KEY, algorithm='HS256') web.setcookie('akey', token, 864000) raise web.seeother('/') return render.login()
def _create_jwt_auth_header(self): payload = { 'ist': 'project', 'iss': self.api_key, 'exp': int(time.time()) + (60*5), # 5 minutes 'jti': '{:f}'.format(random.random()) } return jwt.encode(payload, self.api_secret, algorithm='HS256')
def test_iat_not_int(self, key): claims = { 'iat': 'test' } token = jwt.encode(claims, key) with pytest.raises(JWTError): jwt.decode(token, key)
def _create_jwt_auth_header(self): payload = { 'ist': 'project', 'iss': self.api_key, 'iat': int(time.time()), # current time in unix time (seconds) 'exp': int(time.time()) + (60*3), # 3 minutes in the future (seconds) 'jti': '{0}'.format(0, random.random()) } return jwt.encode(payload, self.api_secret, algorithm='HS256')
def test_jti_string(self, key): jti = 'JWT ID' claims = { 'jti': jti } token = jwt.encode(claims, key) jwt.decode(token, key)
def test_iss_list(self, key): iss = 'issuer' claims = { 'iss': iss } token = jwt.encode(claims, key) jwt.decode(token, key, issuer=['https://issuer', 'issuer'])
def test_subscription_not_expired(): """Test subscription not being expired.""" cl = cloud.Cloud(None, cloud.MODE_DEV) cl.id_token = jwt.encode({ 'custom:sub-exp': '2017-11-13' }, 'test') with patch('homeassistant.util.dt.utcnow', return_value=utcnow().replace(year=2017, month=11, day=9)): assert not cl.subscription_expired
def test_sub_correct(self, key): sub = 'subject' claims = { 'sub': sub } token = jwt.encode(claims, key) jwt.decode(token, key, subject=sub)
def test_iss_tuple(self, key): iss = 'issuer' claims = { 'iss': iss } token = jwt.encode(claims, key) jwt.decode(token, key, issuer=('https://issuer', 'issuer'))
def test_exp_datetime(self, key): exp = datetime.utcnow() + timedelta(seconds=5) claims = { 'exp': exp } token = jwt.encode(claims, key) jwt.decode(token, key)
def test_nbf_datetime(self, key): nbf = datetime.utcnow() - timedelta(seconds=5) claims = { 'nbf': nbf } token = jwt.encode(claims, key) jwt.decode(token, key)
def test_aud_list(self, key): aud = 'audience' claims = { 'aud': [aud] } token = jwt.encode(claims, key) jwt.decode(token, key, audience=aud)
def test_aud_string(self, key): aud = 'audience' claims = { 'aud': aud } token = jwt.encode(claims, key) jwt.decode(token, key, audience=aud)
def test_aud_list_multiple(self, key): aud = 'audience' claims = { 'aud': [aud, 'another'] } token = jwt.encode(claims, key) jwt.decode(token, key, audience=aud)
def test_iss_string(self, key): iss = 'issuer' claims = { 'iss': iss } token = jwt.encode(claims, key) jwt.decode(token, key, issuer=iss)
def test_sub_string(self, key): sub = 'subject' claims = { 'sub': sub } token = jwt.encode(claims, key) jwt.decode(token, key)
def generate_token(user_id): timestamp = _current_timestamp() payload = { "iss": JWT_ISSUER, "iat": int(timestamp), "exp": int(timestamp + JWT_LIFETIME_SECONDS), "sub": str(user_id), } return jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGORITHM)
def test_sub_invalid(self, key): sub = 1 claims = { 'sub': sub } token = jwt.encode(claims, key) with pytest.raises(JWTError): jwt.decode(token, key)
def test_jti_invalid(self, key): jti = 1 claims = { 'jti': jti } token = jwt.encode(claims, key) with pytest.raises(JWTError): jwt.decode(token, key)
def test_invalid_email_value(): encoded_jwt = jwt.encode({"nosub": "email"}, settings.SECRET_KEY, algorithm=settings.ALGORITHM) with pytest.raises(HTTPException) as exinfo: assert validate_token(encoded_jwt) is None assert exinfo.value.detail == "Could not validate credentials"
def create_jwt(data: dict): to_encode = data.copy() encoded_jwt = jwt.encode(to_encode, SECRET, ALGORITHM) return encoded_jwt
def test_ui_extensions_wrong_jwt_secret(self): token = jwt.encode({"banana": 42}, self.wrong_secret) for location in ALL_UI_EXTENSIONS: resp = self.app.get("{}?jwt={}".format(location, token)) self.assertEqual(resp.status_code, 200) self.assertIn("invalid jwt", str(resp.data))
def test_no_alg_default_headers(self, claims, key, headers): token = jwt.encode(claims, key, algorithm='HS384') b64header, b64payload, b64signature = token.split('.') bad_token = b64header + '.' + b64payload with pytest.raises(JWTError): jwt.get_unverified_headers(bad_token)
def test_unverified_claims_object(self, claims, key): token = jwt.encode(claims, key) assert jwt.get_unverified_claims(token) == claims
def get_root_token(electionId): electoral_districts = Area.Model.query.filter( Area.Model.areaType == AreaTypeEnum.ElectoralDistrict, Area.Model.electionId == electionId).all() countries = Area.Model.query.filter( Area.Model.areaType == AreaTypeEnum.Country, Area.Model.electionId == electionId).all() jwt_payload = { ROLE_CLAIM: [ ROLE_PREFIX + ADMIN_ROLE, ROLE_PREFIX + DATA_EDITOR_ROLE, ROLE_PREFIX + POLLING_DIVISION_REPORT_VIEWER_ROLE, ROLE_PREFIX + POLLING_DIVISION_REPORT_VERIFIER_ROLE, ROLE_PREFIX + ELECTORAL_DISTRICT_REPORT_VIEWER_ROLE, ROLE_PREFIX + ELECTORAL_DISTRICT_REPORT_VERIFIER_ROLE, ROLE_PREFIX + NATIONAL_REPORT_VIEWER_ROLE, ROLE_PREFIX + NATIONAL_REPORT_VERIFIER_ROLE, ROLE_PREFIX + EC_LEADERSHIP_ROLE ], SUB: "*****@*****.**", AREA_CLAIM_PREFIX + ADMIN_ROLE: str([]), AREA_CLAIM_PREFIX + DATA_EDITOR_ROLE: str([{ "areaId": electoral_district.areaId, "areaName": electoral_district.areaName } for electoral_district in electoral_districts]), AREA_CLAIM_PREFIX + POLLING_DIVISION_REPORT_VIEWER_ROLE: str([{ "areaId": electoral_district.areaId, "areaName": electoral_district.areaName } for electoral_district in electoral_districts]), AREA_CLAIM_PREFIX + POLLING_DIVISION_REPORT_VERIFIER_ROLE: str([{ "areaId": electoral_district.areaId, "areaName": electoral_district.areaName } for electoral_district in electoral_districts]), AREA_CLAIM_PREFIX + ELECTORAL_DISTRICT_REPORT_VIEWER_ROLE: str([{ "areaId": electoral_district.areaId, "areaName": electoral_district.areaName } for electoral_district in electoral_districts]), AREA_CLAIM_PREFIX + ELECTORAL_DISTRICT_REPORT_VERIFIER_ROLE: str([{ "areaId": electoral_district.areaId, "areaName": electoral_district.areaName } for electoral_district in electoral_districts]), AREA_CLAIM_PREFIX + NATIONAL_REPORT_VIEWER_ROLE: str([{ "areaId": country.areaId, "areaName": country.areaName } for country in countries]), AREA_CLAIM_PREFIX + NATIONAL_REPORT_VERIFIER_ROLE: str([{ "areaId": country.areaId, "areaName": country.areaName } for country in countries]), AREA_CLAIM_PREFIX + EC_LEADERSHIP_ROLE: str([{ "areaId": country.areaId, "areaName": country.areaName } for country in countries]) } # Generate a token with claims for everything. key = "jwt_secret" encoded_jwt_token = jwt.encode(jwt_payload, key) return encoded_jwt_token
def test_invalid_token(): encoded_jwt = jwt.encode({"sub": "username"}, "invalid_secret_key", algorithm=settings.ALGORITHM) with pytest.raises(HTTPException) as exinfo: assert validate_token(encoded_jwt) is None assert exinfo.value.detail == "Could not validate credentials"
def generate_auth_token(data): data["exp"] = datetime.utcnow() + timedelta(seconds=_EXPIRATION) return jwt.encode(data, _SECRET_KEY)
async def post_token_service(data: dict): expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) data.update({"exp": expire}) encoded_jwt = jwt.encode(data, SECRET_KEY, algorithm=ALGORITHM) return TokenRespose(token=encoded_jwt, message="Generated token")
def generate_token(user): secret = 'amf1234' algorithm = 'HS256' token = jwt.encode(user, secret, algorithm) return token
def test_non_default_alg_positional_bwcompat(self, claims, key): encoded = jwt.encode(claims, key, 'HS384') decoded = jwt.decode(encoded, key, 'HS384') assert claims == decoded
def test_subscription_not_expired_without_sub_in_claim(): """Test that we do not enforce subscriptions yet.""" cl = cloud.Cloud(None, cloud.MODE_DEV) cl.id_token = jwt.encode({}, 'test') assert not cl.subscription_expired
def test_at_hash_missing_claim(self, claims, key): token = jwt.encode(claims, key) payload = jwt.decode(token, key, access_token='<ACCESS_TOKEN>') assert 'at_hash' not in payload
def test_at_hash_unable_to_calculate(self, claims, key): token = jwt.encode(claims, key, access_token='<ACCESS_TOKEN>') with pytest.raises(JWTError): jwt.decode(token, key, access_token='\xe2')
def create_access_token(data: dict, expires_delta: timedelta): to_encode = data.copy() expire = datetime.utcnow() + expires_delta to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt
def encode(data): return jwt.encode(data, JWT_SECRET, algorithm=JWT_ALGORITHM)
def encode(payload: dict, private_jwk: dict, algorithm='RS256') -> str: return jwt.encode(payload, key=private_jwk, algorithm=algorithm)
from jose import jwt token = jwt.encode({'key': 'value'}, 'Turing', algorithm='HS256') print token d = jwt.decode(token, 'Turing', algorithms=['HS256']) print d
print("payload {}".format(payload)) payload["exp"] = datetime.datetime.utcnow() + datetime.timedelta(minutes=30) # valid for 30 minutes payload["iat"] = datetime.datetime.utcnow() # Handle RS256 # Build a new private key # openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days XXX # Private Key (RSA) can be retrieved via openssl # openssl rsa -in key.pem -out key.decrypted.pem # Public key (RSA) can be retrieved via openssl # openssl rsa -in key.pem -pubout > key.pub fingerprint_enc = getThumbprintFromHashLib() # Encode privatekey_file = "/home/dougie/onedrive/orion/security/jwt/key.decrypted.pem" # token = jwt.encode(payload, key=open(privatekey_file,"r").read(), algorithm='RS256', headers={"x5t":x5t}) token = jwt.encode(payload, key=open(privatekey_file,"r").read(), algorithm='RS256', headers={"x5t":fingerprint_enc.decode('utf-8')}) print("token -> {}".format(token)) # Decode # Check the types of token and public_key pubkey_file = "/home/dougie/onedrive/orion/security/jwt/key.pub" payload = jwt.decode(token, key=open(pubkey_file,"r").read(), algorithms=['RS256']) print("") print("payload -> {}".format(payload)) if __name__ == '__main__': main()
} TEST_CLAIMS = { "iss": "https://edc.eu.auth0.com/", "aud": 'https://test', "scope": [ 'manage:callbacks', ], "gty": "client-credentials", "email": '*****@*****.**', "permissions": [ 'manage:callbacks', ] } TOKEN = jwt.encode(TEST_CLAIMS, "ysdfvdfvdsvfdsvfdvs", algorithm="HS256") class TestCallbacks(unittest.TestCase): def setUp(self) -> None: self._cache = KeyValueDatabase.instance(provider='inmemory') self._cache.set('heinrich__cubegen', {'value_key': 'value'}) self._cache.set('heinrich__cubegen__cfg', CUBEGEN_TEST) self._cache.set('heinrich2__cubegen', { 'value_key': 'value', 'progress': [ 100, ] }) self._token = jwt.encode(TEST_CLAIMS, "ysdfvdfvdsvfdsvfdvs",
def test_validate_token(): encoded_jwt = jwt.encode({"sub": "username"}, settings.SECRET_KEY, algorithm=settings.ALGORITHM) assert validate_token(encoded_jwt) is None
def create_access_token(data: dict): to_encode = data.copy() expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt
def test_at_hash_missing_access_token(self, claims, key): token = jwt.encode(claims, key, access_token='<ACCESS_TOKEN>') with pytest.raises(JWTError): jwt.decode(token, key)
def encode_token(token_info): return jwt.encode(token_info, JWT_SECRET, algorithm=JWT_ALGORITHM)
def test_at_hash(self, claims, key): access_token = '<ACCESS_TOKEN>' token = jwt.encode(claims, key, access_token=access_token) payload = jwt.decode(token, key, access_token=access_token) assert 'at_hash' in payload
def get_root_token(election): from orm.entities import Area from orm.enums import AreaTypeEnum provinces = Area.get_associated_areas_query( areas=[], areaType=AreaTypeEnum.Province, electionId=election.election.electionId).all() administrative_districts = Area.get_associated_areas_query( areas=[], areaType=AreaTypeEnum.AdministrativeDistrict, electionId=election.election.electionId).all() countries = Area.get_associated_areas_query( areas=[], areaType=AreaTypeEnum.Country, electionId=election.election.electionId).all() jwt_payload = { ROLE_CLAIM: [ ROLE_PREFIX + ADMIN_ROLE, ROLE_PREFIX + DATA_EDITOR_ROLE, ROLE_PREFIX + POLLING_DIVISION_REPORT_VIEWER_ROLE, ROLE_PREFIX + POLLING_DIVISION_REPORT_VERIFIER_ROLE, ROLE_PREFIX + ADMINISTRATIVE_DISTRICT_REPORT_VIEWER_ROLE, ROLE_PREFIX + ADMINISTRATIVE_DISTRICT_REPORT_VERIFIER_ROLE, ROLE_PREFIX + PROVINCIAL_REPORT_VIEWER_ROLE, ROLE_PREFIX + PROVINCIAL_REPORT_VIEWER_ROLE, ROLE_PREFIX + NATIONAL_REPORT_VIEWER_ROLE, ROLE_PREFIX + NATIONAL_REPORT_VERIFIER_ROLE, ROLE_PREFIX + EC_LEADERSHIP_ROLE ], SUB: "*****@*****.**", AREA_CLAIM_PREFIX + ADMIN_ROLE: str([]), AREA_CLAIM_PREFIX + DATA_EDITOR_ROLE: str([{ "areaId": administrative_district.areaId, "areaName": administrative_district.areaName } for administrative_district in administrative_districts]), AREA_CLAIM_PREFIX + POLLING_DIVISION_REPORT_VIEWER_ROLE: str([{ "areaId": administrative_district.areaId, "areaName": administrative_district.areaName } for administrative_district in administrative_districts]), AREA_CLAIM_PREFIX + POLLING_DIVISION_REPORT_VERIFIER_ROLE: str([{ "areaId": administrative_district.areaId, "areaName": administrative_district.areaName } for administrative_district in administrative_districts]), AREA_CLAIM_PREFIX + ADMINISTRATIVE_DISTRICT_REPORT_VIEWER_ROLE: str([{ "areaId": administrative_district.areaId, "areaName": administrative_district.areaName } for administrative_district in administrative_districts]), AREA_CLAIM_PREFIX + ADMINISTRATIVE_DISTRICT_REPORT_VERIFIER_ROLE: str([{ "areaId": administrative_district.areaId, "areaName": administrative_district.areaName } for administrative_district in administrative_districts]), AREA_CLAIM_PREFIX + PROVINCIAL_REPORT_VIEWER_ROLE: str([{ "areaId": province.areaId, "areaName": province.areaName } for province in provinces]), AREA_CLAIM_PREFIX + PROVINCIAL_REPORT_VERIFIER_ROLE: str([{ "areaId": province.areaId, "areaName": province.areaName } for province in provinces]), AREA_CLAIM_PREFIX + NATIONAL_REPORT_VIEWER_ROLE: str([{ "areaId": country.areaId, "areaName": country.areaName } for country in countries]), AREA_CLAIM_PREFIX + NATIONAL_REPORT_VERIFIER_ROLE: str([{ "areaId": country.areaId, "areaName": country.areaName } for country in countries]), AREA_CLAIM_PREFIX + EC_LEADERSHIP_ROLE: str([{ "areaId": country.areaId, "areaName": country.areaName } for country in countries]) } # Generate a token with claims for everything. key = "jwt_secret" encoded_jwt_token = jwt.encode(jwt_payload, key) return encoded_jwt_token
def test_round_trip_with_different_key_types(self, key): token = jwt.encode({'testkey': 'testvalue'}, key, algorithm='HS256') verified_data = jwt.decode(token, key, algorithms=['HS256']) assert 'testkey' in verified_data.keys() assert verified_data['testkey'] == 'testvalue'
def test_non_default_alg(self, claims, key): encoded = jwt.encode(claims, key, algorithm='HS384') decoded = jwt.decode(encoded, key, algorithms='HS384') assert claims == decoded
def test_aud_empty_claim(self, claims, key): aud = 'audience' token = jwt.encode(claims, key) jwt.decode(token, key, audience=aud)
def __generateToken(self, body, claims): return jwt.encode(body, self.__tokenKey(), algorithm='HS256', headers=claims)