def test_answer_with_token(self):
        inst = self.target()
        inst.update({
            'client_id': self.client.id,
            'redirect_uri': self.client.get_redirect_uri(),
            'response_type': 'id_token token',
            'scope': 'openid profile',
            'nonce': 'noncestring',
            'state': 'statestring',
        })
        inst.validate()

        resp = inst.answer(self.provider, self.owner)
        resp.validate()

        token = self.store.get_access_token(resp.access_token)
        self.assertEqual(resp.token_type, token.get_type())
        self.assertEqual(resp.scope, ' '.join(token.get_scope()))
        self.assertEqual(resp.expires_in, token.get_expires_in())

        self.assertEqual(resp.state, 'statestring')

        jwt = JWT(self.jwkset.copy())
        self.assertTrue(jwt.verify(resp.id_token))

        id_token = json.loads(jwt.decode(resp.id_token).decode('utf8'))
        self.assertEqual(id_token['nonce'], 'noncestring')
        self.assertEqual(id_token['at_hash'],
                         self.provider.left_hash(self.client.get_jws_alg(),
                                                 resp.access_token))
Exemple #2
0
 def jwt_encode_handler(keys, payload):
     _jwt = JWT(keys)
     return _jwt.encode({
         "typ": "JWT",
         "alg": JWTSetting.JWT_ALG,
         'kid': JWTSetting.JWT_KID
     }, payload)
Exemple #3
0
 def jwt_encode_handler(keys, payload):
     _jwt = JWT(keys)
     return _jwt.encode(
         {
             "typ": "JWT",
             "alg": JWTSetting.JWT_ALG,
             'kid': JWTSetting.JWT_KID
         }, payload)
Exemple #4
0
class JWTTest(TestCase):
    def setUp(self):
        self.inst = JWT()
        self.key = jwk_from_dict(json.loads(load_testdata('oct.json', 'r')))

        self.message = {
            'iss': 'joe',
            'exp': 1300819380,
            'http://example.com/is_root': True,
        }

        self.compact_jws = (
            'eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9'
            '.'
            'eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFt'
            'cGxlLmNvbS9pc19yb290Ijp0cnVlfQ'
            '.'
            'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk')

    @freeze_time("2011-03-22 18:00:00", tz_offset=0)
    def test_decode(self):
        message = self.inst.decode(self.compact_jws, self.key)
        self.assertEqual(message, self.message)

    def test_decode_with_do_time_check_disabled(self):
        message = self.inst.decode(self.compact_jws,
                                   self.key,
                                   do_time_check=False)
        self.assertEqual(message, self.message)

    def test_expiration(self):
        self.assertRaisesRegex(JWTDecodeError, 'JWT Expired', self.inst.decode,
                               self.compact_jws, self.key)

    def test_no_before_used_before(self):
        compact_jws = self.inst.encode(
            {
                'nbf':
                get_int_from_datetime(
                    datetime.now(timezone.utc) + timedelta(hours=1))
            }, self.key)
        self.assertRaisesRegex(JWTDecodeError, 'JWT Not valid yet',
                               self.inst.decode, compact_jws, self.key)

    def test_no_before_used_after(self):
        message = {
            'nbf':
            get_int_from_datetime(
                datetime.now(timezone.utc) - timedelta(hours=1))
        }
        compact_jws = self.inst.encode(message, self.key)
        self.assertEqual(self.inst.decode(compact_jws, self.key), message)
Exemple #5
0
class JWTTest(TestCase):

    def setUp(self):
        self.inst = JWT()
        self.key = jwk_from_dict(
            json.loads(load_testdata('oct.json', 'r')))

        self.message = {
            'iss': 'joe',
            'exp': 1300819380,
            'http://example.com/is_root': True,
        }

        self.compact_jws = (
            'eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9'
            '.'
            'eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFt'
            'cGxlLmNvbS9pc19yb290Ijp0cnVlfQ'
            '.'
            'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk'
        )

    def test_decode(self):
        message = self.inst.decode(self.compact_jws, self.key)
        self.assertEqual(message, self.message)
Exemple #6
0
    def setUp(self):
        self.inst = JWT()
        self.key = jwk_from_dict(json.loads(load_testdata('oct.json', 'r')))

        self.message = {
            'iss': 'joe',
            'exp': 1300819380,
            'http://example.com/is_root': True,
        }

        self.compact_jws = (
            'eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9'
            '.'
            'eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFt'
            'cGxlLmNvbS9pc19yb290Ijp0cnVlfQ'
            '.'
            'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk')
def verify():
    auth = request.headers.get('Authorization')
    if auth is None or not auth.startswith('Bearer '):
        abort(401, description="Unauthorized")
    token = auth[7:]
    try:
        jwt = JWT(token, claims, 2)
        jwks.verify(jwt)
    except Exception as e:
        abort(403, e)
    def test_answer(self):
        inst = self.target()
        inst.update({
            'client_id': self.client.id,
            'grant_type': 'authorization_code',
            'code': self.code.get_code(),
        })
        inst.validate()

        with mock.patch.object(self.provider, 'authorize_client',
                               return_value=True):
            resp = inst.answer(self.provider, self.owner)

        jwt = JWT(self.jwkset.copy())

        self.assertTrue(jwt.verify(resp.id_token))

        id_token = json.loads(jwt.decode(resp.id_token).decode('utf8'))
        self.assertEqual(
            id_token['at_hash'],
            self.provider.left_hash(self.client.get_jws_alg(),
                                    resp.access_token))
    def test_answer(self):
        inst = self.target()
        inst.update({
            'client_id': self.client.id,
            'redirect_uri': self.client.get_redirect_uri(),
            'response_type': 'id_token',
            'scope': 'openid profile',
            'nonce': 'noncestring',
            'state': 'statestring',
        })
        inst.validate()

        resp = inst.answer(self.provider, self.owner)
        resp.validate()

        self.assertEqual(resp.state, 'statestring')

        jwt = JWT(self.jwkset.copy())
        self.assertTrue(jwt.verify(resp.id_token))

        id_token = json.loads(jwt.decode(resp.id_token).decode('utf8'))
        self.assertEqual(id_token['nonce'], 'noncestring')
Exemple #10
0
    def test_answer(self):
        inst = self.target()
        inst.update({
            'client_id': self.client.id,
            'grant_type': 'authorization_code',
            'code': self.code.get_code(),
        })
        inst.validate()

        with mock.patch.object(self.provider,
                               'authorize_client',
                               return_value=True):
            resp = inst.answer(self.provider, self.owner)

        jwt = JWT(self.jwkset.copy())

        self.assertTrue(jwt.verify(resp.id_token))

        id_token = json.loads(jwt.decode(resp.id_token).decode('utf8'))
        self.assertEqual(
            id_token['at_hash'],
            self.provider.left_hash(self.client.get_jws_alg(),
                                    resp.access_token))
Exemple #11
0
    def encode_token(self, token, client, access_token=None):
        assert isinstance(token, IDToken)
        assert isinstance(client, IClient)
        assert isinstance(access_token, (str, type(None)))

        jwkset = self.jwkset.copy()
        if access_token:
            jwkset.append(JWK.from_dict({
                'kty': 'oct',
                'k': access_token,
            }))

        jwt = JWT(jwkset)
        jws = jwt.encode(dict(alg=client.get_jws_alg()),
                         token.to_json().encode('utf8'))

        if not self.is_token_encryption_enabled:
            return jws

        jwe = jwt.encode(
            dict(alg=client.get_jwe_alg(), enc=client.get_jwe_enc(),
                 cty='JWT'), jws)
        return jwe
Exemple #12
0
    def encode_token(self, token, client, access_token=None):
        assert isinstance(token, IDToken)
        assert isinstance(client, IClient)
        assert isinstance(access_token, (str, type(None)))

        jwkset = self.jwkset.copy()
        if access_token:
            jwkset.append(JWK.from_dict({
                'kty': 'oct',
                'k': access_token,
            }))

        jwt = JWT(jwkset)
        jws = jwt.encode(dict(alg=client.get_jws_alg()),
                         token.to_json().encode('utf8'))

        if not self.is_token_encryption_enabled:
            return jws

        jwe = jwt.encode(dict(alg=client.get_jwe_alg(),
                              enc=client.get_jwe_enc(),
                              cty='JWT'),
                         jws)
        return jwe
Exemple #13
0
 def jwt_decode_handler(keys, jwt):
     _jwt = JWT(keys)
     return _jwt.decode(jwt)
Exemple #14
0
 def jwt_target(keys):
     return JWT(keys)
Exemple #15
0
 def jwt_verify(keys, jwt):
     _jwt = JWT(keys)
     return _jwt.verify(jwt)
Exemple #16
0
 def jwt_verify(keys, jwt):
     _jwt = JWT(keys)
     return _jwt.verify(jwt)
Exemple #17
0
from jwt.jwks import JWKS
from jwt.jwt import JWT
import os
import traceback

try:
    jwks = JWKS(os.environ['OKTA_ISSUER_URI'] + '/v1/keys')
    token = 'eyJraWQiOiJCcTJqc1JSLXJDeFM4aDN2dE9Ib2JUZDJVZEFSZDAzSHdJUmdCOFByUllJIiwiYWxnIjoiUlMyNTYifQ.eyJ2ZXIiOjEsImp0aSI6IkFULmVaOVpMSXV1aWVaR3A4c3FPSjVoalJxbnVsM2xSQWJUdmhwVFZPV21SS0kiLCJpc3MiOiJodHRwczovL2Rldi00MzYyNTYub2t0YS5jb20vb2F1dGgyL2RlZmF1bHQiLCJhdWQiOiJhcGk6Ly9kZWZhdWx0IiwiaWF0IjoxNjA2MTMzMjI5LCJleHAiOjE2MDYxMzY4MjksImNpZCI6IjBvYWF2c3FwMllGUlJUTDV4NWQ1IiwidWlkIjoiMDB1NnloODhWcEFSbzdpdVg1ZDUiLCJzY3AiOlsib3BlbmlkIiwiZW1haWwiXSwic3ViIjoicGhpbGxpcC5lZHdhcmRzQHRvcHRhbC5jb20ifQ.LzZLlgHqXzhtm-garhgYRfvqFLuy2M2gKMJ-8nkaUxHRkvKoE9zp4S4Kr0ReRThQCB8oa5dexqnXpvena1eWMAWrF31ATSCaCAjhfNjp-Y4z-wwj312AKRvhJghKfymIo-rx8Yh6_stf3Y0ZsdYvCo1ORgQ5vjzOzH5VzKrkkl1qL5Zau0FB0Ot4jQFSMYXbYsQEm9XFpaD65wGyEoKwd940ZXakFQfJEB_ooWDlgDjhoKtiZWuC7GAUozNPOEmCmqfCB-IV0U-VLIaZzFOGS3I42up59gu3Xy18nY3ZvznuinZcD7vuetu33CQ8nSMajd3LrkRKLzgZWTQjue0GkQ'
    claims = {'iss': os.environ['OKTA_ISSUER_URI'], 'aud': 'api://default'}
    jwt = JWT(token, claims, 7)
    print(jwt)
    jwks.verify(jwt)
except Exception as e:
    print('Exception', e)
Exemple #18
0
 def jwt_decode_handler(keys, jwt):
     _jwt = JWT(keys)
     return _jwt.decode(jwt)