How to use jwt - 10 common examples

To help you get started, we’ve selected a few jwt examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github stormpath / stormpath-sdk-python / tests / live / test_resource.py View on Github external
def test_building_id_site_redirect_uri(self):
        try:
            from urlparse import urlparse
        except ImportError:
            from urllib.parse import urlparse

        ret = self.app.build_id_site_redirect_url('http://localhost/')
        try:
            jwt_response = urlparse(ret).query.split('=')[1]
        except:
            self.fail("Failed to parse ID site redirect uri")

        try:
            decoded_data = jwt.decode(
                jwt_response, verify=False, algorithms=['HS256'])
        except jwt.DecodeError:
            self.fail("Invaid JWT generated.")

        self.assertIsNotNone(decoded_data.get('iat'))
        self.assertIsNotNone(decoded_data.get('jti'))
        self.assertIsNotNone(decoded_data.get('iss'))
        self.assertEqual(decoded_data.get('iss'), self.app._client.auth.id)
        self.assertIsNotNone(decoded_data.get('sub'))
        self.assertIsNotNone(decoded_data.get('cb_uri'))
        self.assertEqual(decoded_data.get('cb_uri'), 'http://localhost/')
        self.assertIsNone(decoded_data.get('path'))
        self.assertIsNone(decoded_data.get('state'))


        ret = self.app.build_id_site_redirect_url(
                'http://testserver/',
                path='/#/register',
github dcos / dcos / packages / dcos-integration-test / extra / test_iam.py View on Github external
{'uid': serviceuid, 'exp': time.time() + 30},
        default_rsa_privkey,
        algorithm='RS256'
    ).decode('ascii')

    # Log in via the service login token.
    r = noauth_api_session.post(
        '/acs/api/v1/auth/login',
        json={'uid': serviceuid, 'token': service_login_token}
    )
    assert r.status_code == 200, r.text

    # Confirm that the response body contains a DC/OS authentication token.
    token = r.json()['token']
    header_bytes, payload_bytes, signature_bytes = [
        base64url_decode(_.encode('ascii')) for _ in token.split(".")]

    header_dict = json.loads(header_bytes.decode('ascii'))
    assert header_dict['alg'] == 'RS256'
    assert header_dict['typ'] == 'JWT'

    payload_dict = json.loads(payload_bytes.decode('ascii'))
    assert 'exp' in payload_dict
    assert 'uid' in payload_dict
    assert payload_dict['uid'] == serviceuid

    # Verify that the service user account appears in the users collection.
    r = dcos_api_session.get('/acs/api/v1/users', query='type=service')
    uids = [o['uid'] for o in r.json()['array']]
    assert serviceuid in uids

    # Delete the service user account.
github snowflakedb / snowflake-connector-python / test / test_ocsp_ssd.py View on Github external
"""
    host_spec_path = path.join(ocsp.OCSP_CACHE.CACHE_DIR,"host_spec_bypass_ssd.ssd")

    with open(host_spec_path, "w") as jwt_host_spec_fp:
        tdelta = timedelta(days=1)
        nbf_val = datetime.utcnow()
        exp_val = nbf_val+tdelta
        header = {'ssd_iss':'dep1'}
        payload = {}
        hname_string = " ".join(hostname)
        acc_name = ocsp.get_account_from_hostname(hostname[0])
        payload.update({'sfcEndpoint': hname_string})
        payload.update({'certId': '*'})
        payload.update({'nbf': nbf_val})
        payload.update({'exp': exp_val})
        host_spec_jwt_token = jwt.encode(payload, priv_key, algorithm='RS512', headers=header)
        host_spec_bypass_ssd = {acc_name: host_spec_jwt_token.decode("utf-8")}
        json.dump(host_spec_bypass_ssd, jwt_host_spec_fp)
github vimalloc / flask-jwt-extended / tests / test_protected_endpoints.py View on Github external
with self.app.test_request_context():
            token = encode_access_token('foo', 'newsecret', 'HS256',
                                        timedelta(minutes=5), True, {},
                                        csrf=False, identity_claim='identity')
        auth_header = "Bearer {}".format(token)
        response = self.client.get('/partially-protected',
                                   headers={'Authorization': auth_header})
        data = json.loads(response.get_data(as_text=True))
        status_code = response.status_code
        self.assertEqual(status_code, 422)
        self.assertIn('msg', data)

        # Test with valid token that is missing required claims
        now = datetime.utcnow()
        token_data = {'exp': now + timedelta(minutes=5)}
        encoded_token = jwt.encode(token_data, self.app.config['SECRET_KEY'],
                                   self.app.config['JWT_ALGORITHM']).decode('utf-8')
        auth_header = "Bearer {}".format(encoded_token)
        response = self.client.get('/partially-protected',
                                   headers={'Authorization': auth_header})
        data = json.loads(response.get_data(as_text=True))
        status_code = response.status_code
        self.assertEqual(status_code, 422)
        self.assertIn('msg', data)
github dusktreader / flask-praetorian / tests / test_base.py View on Github external
validate(), it is called an any exceptions it raises are wrapped
              in an InvalidUserError
            * verifies that custom claims may be encoded in the token and
              validates that the custom claims do not collide with reserved
              claims
        """
        guard = Praetorian(app, user_class)
        the_dude = user_class(
            username='TheDude',
            password=guard.hash_password('abides'),
            roles='admin,operator',
        )
        moment = pendulum.parse('2017-05-21 18:39:55')
        with freezegun.freeze_time(moment):
            token = guard.encode_jwt_token(the_dude)
            token_data = jwt.decode(
                token, guard.encode_key, algorithms=guard.allowed_algorithms,
            )
            assert token_data['iat'] == moment.int_timestamp
            assert token_data['exp'] == (
                moment + DEFAULT_JWT_ACCESS_LIFESPAN
            ).int_timestamp
            assert token_data[REFRESH_EXPIRATION_CLAIM] == (
                moment + DEFAULT_JWT_REFRESH_LIFESPAN
            ).int_timestamp
            assert token_data['id'] == the_dude.id
            assert token_data['rls'] == 'admin,operator'

        moment = pendulum.parse('2017-05-21 18:39:55')
        override_access_lifespan = pendulum.Duration(minutes=1)
        override_refresh_lifespan = pendulum.Duration(hours=1)
        with freezegun.freeze_time(moment):
github liqd / adhocracy3 / src / adhocracy_core / adhocracy_core / authentication / test_init.py View on Github external
def test_unauthenticated_userid_return_none_if_not_jwt_token(
        self, inst, request_, mocker):
        from jwt import DecodeError
        from . import UserTokenHeader
        mocker.patch('jwt.decode', side_effect=DecodeError)
        request_.headers[UserTokenHeader] = 'tokenhash'
        assert inst.unauthenticated_userid(request_) is None
github testdrivenio / testdriven-app-2.5 / services / users / project / api / models.py View on Github external
def decode_auth_token(auth_token):
        """
        Decodes the auth token - :param auth_token: - :return: integer|string
        """
        try:
            payload = jwt.decode(
                auth_token, current_app.config.get('SECRET_KEY'))
            return payload['sub']
        except jwt.ExpiredSignatureError:
            return 'Signature expired. Please log in again.'
        except jwt.InvalidTokenError:
            return 'Invalid token. Please log in again.'
github yandex-cloud / python-sdk / tests / test_service_account_auth.py View on Github external
def test_service_account_key(service_account_key):
    request_func = get_auth_token_requester(service_account_key=service_account_key).get_token_request
    request = request_func()
    now = int(time.time())
    headers = jwt.get_unverified_header(request.jwt)
    parsed = jwt.decode(request.jwt, secret=service_account_key["public_key"], algorithms=['PS256'], verify=False)
    assert headers["typ"] == "JWT"
    assert headers["alg"] == "PS256"
    assert headers["kid"] == service_account_key["id"]

    assert parsed["iss"] == service_account_key["service_account_id"]
    assert parsed["aud"] == "https://iam.api.cloud.yandex.net/iam/v1/tokens"
    assert now - 60 <= int(parsed["iat"]) <= now
github twilio / twilio-python / tests / unit / jwt / test_jwt.py View on Github external
def assertJwtsEqual(self, jwt, key, expected_payload=None, expected_headers=None):
        expected_headers = expected_headers or {}
        expected_payload = expected_payload or {}

        decoded_payload = jwt_lib.decode(jwt, key, verify=False)
        decoded_headers = jwt_lib.get_unverified_header(jwt)

        self.assertEqual(expected_headers, decoded_headers)
        self.assertEqual(expected_payload, decoded_payload)
github vimalloc / flask-jwt-extended / tests / test_jwt_encode_decode.py View on Github external
def test_decode_invalid_jwt(self):
        with self.app.test_request_context():
            identity_claim = 'identity'
            # Verify underlying pyjwt expires verification works
            with self.assertRaises(jwt.ExpiredSignatureError):
                token_data = {
                    'exp': datetime.utcnow() - timedelta(minutes=5),
                }
                encoded_token = jwt.encode(token_data, 'secret', 'HS256').decode('utf-8')
                decode_jwt(encoded_token, 'secret', 'HS256',
                           csrf=False, identity_claim=identity_claim)

            # Missing jti
            with self.assertRaises(JWTDecodeError):

                token_data = {
                    'exp': datetime.utcnow() + timedelta(minutes=5),
                    identity_claim: 'banana',
                    'type': 'refresh'
                }
                encoded_token = jwt.encode(token_data, 'secret', 'HS256').decode('utf-8')