Exemplo n.º 1
0
 def validate_claims(self, id_token, params):
     jwt = JWT()
     claims = jwt.decode(id_token,
                         'secret',
                         claims_cls=HybridIDToken,
                         claims_params=params)
     claims.validate()
Exemplo n.º 2
0
 def validate_claims(self, id_token, params):
     jwt = JWT(['HS256'])
     claims = jwt.decode(id_token,
                         'secret',
                         claims_cls=ImplicitIDToken,
                         claims_params=params)
     claims.validate()
Exemplo n.º 3
0
    def test_authorize_token(self):
        self.prepare_data()
        rv = self.client.post('/oauth/authorize', data={
            'response_type': 'code',
            'client_id': 'code-client',
            'state': 'bar',
            'scope': 'openid profile',
            'redirect_uri': 'https://a.b',
            'user_id': '1'
        })
        self.assertIn('code=', rv.location)

        params = dict(url_decode(urlparse.urlparse(rv.location).query))
        self.assertEqual(params['state'], 'bar')

        code = params['code']
        headers = self.create_basic_header('code-client', 'code-secret')
        rv = self.client.post('/oauth/token', data={
            'grant_type': 'authorization_code',
            'redirect_uri': 'https://a.b',
            'code': code,
        }, headers=headers)
        resp = json.loads(rv.data)
        self.assertIn('access_token', resp)
        self.assertIn('id_token', resp)

        jwt = JWT()
        claims = jwt.decode(
            resp['id_token'], 'secret',
            claims_cls=CodeIDToken,
            claims_options={'iss': {'value': 'Authlib'}}
        )
        claims.validate()
Exemplo n.º 4
0
    def test_init_algorithms(self):
        _jwt = JWT(['RS256'])
        self.assertRaises(UnsupportedAlgorithmError, _jwt.encode,
                          {'alg': 'HS256'}, {}, 'k')

        _jwt = JWT('RS256')
        self.assertRaises(UnsupportedAlgorithmError, _jwt.encode,
                          {'alg': 'HS256'}, {}, 'k')
Exemplo n.º 5
0
 def fetch_user_info(self):
     options = {
         'iss' : {'essential':True, 'value':self.issuer},
         'aud' : {'essential':True, 'value':self.client_id},
         'exp' : {'essential':True}
     }
     id_token = JWT().decode(self.token['id_token'], self.load_key, claims_options=options)
     id_token.validate() # checking signature is not strictly necessary but let's do it anyway
     sub = self.name + '/' + id_token.sub
     return UserInfo(sub=sub)
Exemplo n.º 6
0
def _jwt_encode(alg, payload, key):
    jwt = JWT(algorithms=alg)
    header = {'alg': alg}
    if isinstance(key, dict):
        # JWK set format
        if 'keys' in key:
            key = random.choice(key['keys'])
            header['kid'] = key['kid']
        elif 'kid' in key:
            header['kid'] = key['kid']

    return to_native(jwt.encode(header, payload, key))
Exemplo n.º 7
0
def validate_token(response):
    id_token = response.get('id_token', None)
    keys = requests.get('https://id.twitch.tv/oauth2/keys').json()
    jwt = JWT()
    claims = jwt.decode(id_token, keys, claims_cls=CodeIDToken)

    try:
        claims.validate()
    except errors.InvalidClaimError:
        pass
    except errors.InvalidTokenError:
        pass
Exemplo n.º 8
0
    def generate_id_token(self,
                          token,
                          request,
                          nonce=None,
                          auth_time=None,
                          code=None):
        scopes = scope_to_list(token['scope'])
        if not scopes or scopes[0] != 'openid':
            return None

        # TODO: merge scopes and claims
        user_info = self.generate_user_info(request.user, scopes)

        now = int(time.time())
        if auth_time is None:
            auth_time = now

        config = self.server.config
        payload = {
            'iss': config['jwt_iss'],
            'aud': [request.client.client_id],
            'iat': now,
            'exp': now + config['jwt_exp'],
            'auth_time': auth_time,
        }
        if nonce:
            payload['nonce'] = nonce

        # calculate at_hash
        alg = config['jwt_alg']

        access_token = token.get('access_token')
        if access_token:
            payload['at_hash'] = to_native(create_half_hash(access_token, alg))

        # calculate c_hash
        if code:
            payload['c_hash'] = to_native(create_half_hash(code, alg))

        payload.update(user_info)
        jwt = JWT(algorithms=alg)
        header = {'alg': alg}

        key = config['jwt_key']
        if isinstance(key, dict):
            # JWK set format
            if 'keys' in key:
                key = random.choice(key['keys'])
                header['kid'] = key['kid']
            elif 'kid' in key:
                header['kid'] = key['kid']

        return to_native(jwt.encode(header, payload, key))
Exemplo n.º 9
0
def parse_openid(client, response, nonce=None):
    jwk_set = _get_google_jwk_set(client)
    id_token = response['id_token']
    claims_params = dict(nonce=nonce,
                         client_id=client.client_id,
                         access_token=response['access_token'])
    jwt = JWT()
    claims = jwt.decode(
        id_token,
        key=jwk_set,
        claims_cls=CodeIDToken,
        claims_options=GOOGLE_CLAIMS_OPTIONS,
        claims_params=claims_params,
    )
    claims.validate(leeway=120)
    return UserInfo(claims)
Exemplo n.º 10
0
    def generate_id_token(self,
                          token,
                          request,
                          nonce=None,
                          auth_time=None,
                          code=None):

        scopes = scope_to_list(token['scope'])
        if not scopes or scopes[0] != 'openid':
            return None

        # TODO: merge scopes and claims
        user_info = self.generate_user_info(request.user, scopes)

        now = int(time.time())
        if auth_time is None:
            auth_time = now

        config = self.server.config
        payload = {
            'iss': config['jwt_iss'],
            'aud': [request.client.client_id],
            'iat': now,
            'exp': now + token['expires_in'],
            'auth_time': auth_time,
        }
        if nonce:
            payload['nonce'] = nonce

        # calculate at_hash
        alg = config.get('jwt_alg', 'HS256')

        access_token = token.get('access_token')
        if access_token:
            at_hash = to_unicode(create_half_hash(access_token, alg))
            payload['at_hash'] = at_hash

        # calculate c_hash
        if code:
            payload['c_hash'] = to_unicode(create_half_hash(code, alg))

        payload.update(user_info)
        jwt = JWT(algorithms=alg)
        header = {'alg': alg}
        key = config['jwt_key']
        id_token = jwt.encode(header, payload, key)
        return to_unicode(id_token)
Exemplo n.º 11
0
from authlib.specs.rfc7519 import JWT
from authlib.deprecate import deprecate
from .claims import get_claim_cls_by_response_type

jwt = JWT()


def parse_id_token(id_token, key):
    deprecate('"parse_id_token" is deprecated, use JWT instead.', 0.8)
    claims = jwt.decode(id_token, key)
    return claims, claims.header


def verify_id_token(response,
                    key,
                    response_type='code',
                    issuers=None,
                    client_id=None,
                    nonce=None,
                    max_age=None,
                    now=None):
    deprecate('"verify_id_token" is deprecated, use JWT instead.', 0.8)
    if 'id_token' not in response:
        raise ValueError('Invalid OpenID response')

    claims_cls = get_claim_cls_by_response_type(response_type)
    claims_request = {
        'access_token': response.get('access_token'),
        'client_id': client_id,
        'nonce': nonce,
        'max_age': max_age