Ejemplo n.º 1
0
 def check_token_response(settings, client_config, resp, sub='a'):
     assert resp.status_code == 200
     data = json.loads(resp.content.decode('utf-8'))
     assert 'access_token' in data
     assert data['token_type'] == 'Bearer'
     assert 'refresh_token' in data
     assert data['expires_in'] == settings.OPENID_DEFAULT_ACCESS_TOKEN_TTL
     assert 'id_token' in data
     database_at = OpenIDToken.objects.get(token_hash=OpenIDToken.get_token_hash(data['access_token']))
     assert database_at.user.username == 'a'
     assert database_at.client == client_config
     assert database_at.token_type == OpenIDToken.TOKEN_TYPE_ACCESS_BEARER_TOKEN
     database_rt = OpenIDToken.objects.get(token_hash=OpenIDToken.get_token_hash(data['refresh_token']))
     assert database_rt.user.username == 'a'
     assert database_rt.client == client_config
     assert database_rt.token_type == OpenIDToken.TOKEN_TYPE_REFRESH_TOKEN
     # validate id token
     header, payload = JWTTools.validate_jwt(data['id_token'])
     assert header['alg'] == 'RS256'
     assert header['typ'] == 'JWT'
     assert payload['exp'] == int(payload['exp'])
     assert payload['iat'] == int(payload['iat'])
     assert payload['aud'] == ['test']
     assert payload['sub'] == sub  # username
     assert payload['iss'] == 'http://testserver/'
Ejemplo n.º 2
0
def extract_access_token(request, forbidden_on_not_present):
    auth_header = request.META.get('HTTP_AUTHORIZATION', None)
    access_token = None
    try:
        if auth_header is not None:
            access_token = get_access_token_from_auth_header(auth_header)
        if request.method == 'POST' and not access_token:
            access_token = get_access_token_from_post_data(request)
        if not access_token:
            access_token = get_access_token_from_uri_query(request.GET)
        if not access_token:
            if forbidden_on_not_present:
                return HttpResponseForbidden('No access token provided')
            else:
                return None
        try:
            db_access_token = OpenIDToken.objects.get(
                token_hash=OpenIDToken.get_token_hash(access_token))
            if db_access_token.expiration < timezone.now():
                return HttpResponseForbidden('Expired access token')
            return db_access_token
        except OpenIDToken.DoesNotExist:
            return HttpResponseForbidden('Provided access token %s not found' %
                                         access_token)
    except BaseException as e:
        return HttpResponseForbidden('Access error: %s' % e)
    def test_client_registration_ok(self, client, openid_client, user):
        token = OpenIDToken.create_token(
            openid_client, OpenIDToken.TOKEN_TYPE_CLIENT_DYNAMIC_REGISTRATION,
            {}, 1e9, user)[0]
        resp = client.post('/openid/register',
                           json.dumps({
                               'redirect_uris':
                               ['http://test.org/auth/complete'],
                               'another':
                               1
                           }),
                           content_type='application/json',
                           HTTP_AUTHORIZATION=self.format_auth(token))

        assert resp.status_code == 201
        content = json.loads(resp.content.decode('utf-8'))
        assert 'client_id' in content
        assert 'client_secret' in content
        client_id = content.pop('client_id')
        client_secret = content.pop('client_secret')
        registration_access_token = content.pop('registration_access_token')
        assert len(registration_access_token) > 32
        registration_client_uri = content.pop('registration_client_uri')
        assert registration_client_uri.startswith(
            'http://testserver/openid/client_configuration/')
        assert content == {
            'another': 1,
            'client_secret_expires_at': 0,
            'redirect_uris': ['http://test.org/auth/complete']
        }

        client = OpenIDClient.objects.get(client_id=client_id)
        assert client.check_client_secret(client_secret)
    def dispatch(self, request, *args, **kwargs):
        id_token_hint = request.GET.get('id_token_hint', None)
        post_logout_redirect_uri = request.GET.get('post_logout_redirect_uri',
                                                   '/')
        state = request.GET.get('state', None)

        if not id_token_hint:
            return HttpResponseForbidden('Must supply id_token_hint parameter')

        # remove all tokens associated with the user
        token = OpenIDToken.objects.filter(
            token_hash=OpenIDToken.get_token_hash(id_token_hint)).first()
        if not token:
            return HttpResponseForbidden('Invalid token')

        root_token = token.root_token
        root_token.related_tokens.all().delete()
        root_token.delete()

        # create next uri
        next_url = post_logout_redirect_uri
        if state:
            if '?' in next_url:
                next_url += '&'
            else:
                next_url += '?'
            next_url += 'state=' + quote(state)

        # and call logout on this server to remove any session we might have with the user
        return HttpResponseRedirect(settings.LOGOUT_URL + '?next=' +
                                    quote(next_url))
    def dispatch(self, request, *args, **kwargs):
        if request.method not in ('GET', 'POST'):
            return HttpResponseBadRequest(
                'Only GET or POST are supported on OpenID endpoint')

        authorization_request_start.send('auth', request=request)

        try:
            resp = self.unpack_auth_parameters(request)
            if resp:
                return resp

            self.validate_max_age()

            client = self._get_client_or_raise_exception()

            if self.should_login(request):
                return self.authenticate(request)

            signal_responses = before_user_consent.send(type(client),
                                                        openid_client=client,
                                                        user=request.user)

            for resp in signal_responses:
                if isinstance(resp[1], HttpResponse):
                    return resp[1]

            should_sign_consent = self.should_request_user_consent(
                request, client)

            if should_sign_consent:
                return self.request_user_consent(request, client)

            if 'code' in self.request_parameters.response_type:
                self.request_parameters.username = request.user.username
                auth_token, auth_db_token = \
                    OpenIDToken.create_token(client=client, token_type=OpenIDToken.TOKEN_TYPE_AUTH,
                                             token_data=self.request_parameters.to_dict(),
                                             ttl=getattr(settings, 'OPENID_AUTH_TOKEN_TTL', 20),
                                             user=request.user)
                authorization_request_finish.send('auth',
                                                  request=request,
                                                  openid_client=client,
                                                  token=auth_token)
                return self.oauth_send_answer(request, {'code': auth_token})
            else:
                raise OAuthError(
                    error='parameter_not_supported',
                    error_description='Only "code" value of the "response_type" '
                    'is supported by this server')

        except OAuthError as err:
            return self.oauth_send_answer(
                request, {
                    'error': err.error,
                    'error_description': err.error_description
                })
    def test_client_registration_bad_token2(self, client, openid_client, user):
        token = OpenIDToken.create_token(
            openid_client, OpenIDToken.TOKEN_TYPE_ACCESS_BEARER_TOKEN, {}, 1e9,
            user)[0]
        resp = client.post('/openid/register',
                           json.dumps({}),
                           content_type='application/json',
                           HTTP_AUTHORIZATION=self.format_auth(token))

        assert resp.status_code == 403
    def test_client_registration_no_redirect_uri(self, client, openid_client,
                                                 user):
        token = OpenIDToken.create_token(
            openid_client, OpenIDToken.TOKEN_TYPE_CLIENT_DYNAMIC_REGISTRATION,
            {}, 1e9, user)[0]
        resp = client.post('/openid/register',
                           json.dumps({}),
                           content_type='application/json',
                           HTTP_AUTHORIZATION=self.format_auth(token))

        assert resp.status_code == 400
        assert json.loads(resp.content.decode('utf-8')) == {
            'error':
            'invalid_request',
            'error_description':
            'Required parameter with name "redirect_uris" is not present'
        }
 def make_registration_response(request, client, client_secret):
     resp = {}
     resp.update(client.client_registration_data)
     resp.update({
         "client_id": client.client_id,
         "client_secret": client_secret,
         "client_secret_expires_at": 0,
     })
     if request.openid_access_token:
         user = request.openid_access_token.user
     else:
         user = User.objects.get(username='******')
     registration_access_token, registration_access_db_token = \
         OpenIDToken.create_token(client, OpenIDToken.TOKEN_TYPE_CLIENT_CONFIGURATION_TOKEN,
                                  {}, OpenIDToken.INFINITE_TTL, user)
     resp.update({
         'registration_access_token':
         registration_access_token,
         'registration_client_uri':
         request.build_absolute_uri(
             reverse('openid_connect_op:client_configuration',
                     kwargs=dict(client_id=client.client_id)))
     })
     return resp