Exemple #1
0
def generate_access_tokens(request: WSGIRequest, user: User):
    # generate bearer token
    bearer_token = BearerToken(OAuth2Validator())
    request.scopes = ["read", "write"]
    request.state = None
    request.extra_credentials = None
    request.grant_type = 'client_credentials'
    request.client = Application.objects.get(
        client_id=settings.SOCIAL_AUTH_CLIENT_ID,
        client_secret=settings.SOCIAL_AUTH_CLIENT_SECRET)
    token = bearer_token.create_token(request)

    # generate JWT
    issuer = settings.JWT_ISSUER
    payload_enricher = getattr(settings, 'JWT_PAYLOAD_ENRICHER', None)
    extra_data = {'username': user.username} if user else {}
    jwt_request = HttpRequest()
    jwt_request.POST = extra_data
    if payload_enricher:
        fn = import_string(payload_enricher)
        extra_data.update(fn(jwt_request))
    payload = generate_payload(issuer, token['expires_in'], **extra_data)
    token['access_token_jwt'] = encode_jwt(payload)

    return token
def test_oidc_endpoint_generation(oauth2_settings, rf):
    oauth2_settings.OIDC_ISS_ENDPOINT = ""
    django_request = rf.get("/")
    request = Request("/", headers=django_request.META)
    validator = OAuth2Validator()
    oidc_issuer_endpoint = validator.get_oidc_issuer_endpoint(request)
    assert oidc_issuer_endpoint == "http://testserver/o"
def test_validate_id_token_expired_jwt(oauth2_settings, mocker, oidc_tokens):
    mocker.patch("oauth2_provider.oauth2_validators.jwt.JWT",
                 side_effect=jwt.JWTExpired)
    validator = OAuth2Validator()
    status = validator.validate_id_token(oidc_tokens.id_token, ["openid"],
                                         mocker.sentinel.request)
    assert status is False
Exemple #4
0
    def setUp(self):
        self.validator = OAuth2Validator()
        self.request = mock.MagicMock(wraps=Request)
        self.resource_server_user = UserModel.objects.create_user(
            "resource_server", "*****@*****.**", "123456")

        self.application = Application(
            name="Test Application",
            redirect_uris=
            "http://localhost http://example.com http://example.org",
            user=self.resource_server_user,
            client_type=Application.CLIENT_CONFIDENTIAL,
            authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
        )
        self.application.save()

        self.resource_server_token = AccessToken.objects.create(
            user=self.resource_server_user,
            token="12345678900",
            application=self.application,
            expires=timezone.now() + datetime.timedelta(days=1),
            scope="introspection")

        self.invalid_token = AccessToken.objects.create(
            user=self.resource_server_user,
            token="12345678901",
            application=self.application,
            expires=timezone.now() + datetime.timedelta(days=-1),
            scope="read write dolphin")

        oauth2_settings._SCOPES = ["read", "write", "introspection", "dolphin"]
        oauth2_settings.RESOURCE_SERVER_INTROSPECTION_URL = "http://example.org/introspection"
        oauth2_settings.RESOURCE_SERVER_AUTH_TOKEN = self.resource_server_token.token
        oauth2_settings.READ_SCOPE = "read"
        oauth2_settings.WRITE_SCOPE = "write"
    def authenticate(self, request):
        auth = request.META.get('HTTP_X_AUTHENTICATION')
        if not auth:
            return None

        username = extract_username(auth)

        # raises User.DoesNotExist should result in 404
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            raise exceptions.NotFound()

        # these are for compatability with OAuth2Validator
        # TODO remove if it becomes possible
        if not hasattr(request, 'headers'):
            request.headers = request.META

        if not hasattr(request, 'client'):
            request.client = None

        # populates request.client with Application if successful
        validator = OAuth2Validator()
        authenticated = validator.authenticate_client(request)
        if not authenticated:
            raise exceptions.AuthenticationFailed('No such application')

        return (user, request.client)
def test_validate_id_token_bad_token_no_aud(oauth2_settings, mocker, oidc_key):
    token = jwt.JWT(header=json.dumps({"alg": "RS256"}),
                    claims=json.dumps({"bad": "token"}))
    token.make_signed_token(oidc_key)
    validator = OAuth2Validator()
    status = validator.validate_id_token(token.serialize(), ["openid"],
                                         mocker.sentinel.request)
    assert status is False
Exemple #7
0
 def _validate(request, *args, **kwargs):
     validator = OAuth2Validator()
     core = OAuthLibCore(Server(validator))
     valid, oauthlib_req = core.verify_request(request, scopes = _scopes)
     if valid:
         request.client = oauthlib_req.client
         request.resource_owner = oauthlib_req.user
         return view_func(request, *args, **kwargs)
     return HttpResponseForbidden()
def get_oauthlib_core():
    """
    Utility function that take a request and returns an instance of `oauth2_provider.backends.OAuthLibCore`
    """
    from oauth2_provider.oauth2_validators import OAuth2Validator
    from oauthlib.oauth2 import Server

    server = Server(OAuth2Validator())
    return OAuthLibCore(server)
def test_get_jwt_bearer_token(oauth2_settings, mocker):
    # oauthlib instructs us to make get_jwt_bearer_token call get_id_token
    request = mocker.MagicMock(wraps=Request)
    validator = OAuth2Validator()
    mock_get_id_token = mocker.patch.object(validator, "get_id_token")
    validator.get_jwt_bearer_token(None, None, request)
    assert mock_get_id_token.call_count == 1
    assert mock_get_id_token.call_args[0] == (None, None, request)
    assert mock_get_id_token.call_args[1] == {}
Exemple #10
0
 def setUp(self):
     self.user = UserModel.objects.create_user("user", "*****@*****.**", "123456")
     self.request = mock.MagicMock(wraps=Request)
     self.request.user = self.user
     self.request.grant_type = "not client"
     self.validator = OAuth2Validator()
     self.application = Application.objects.create(
         client_id="client_id", client_secret="client_secret", user=self.user,
         client_type=Application.CLIENT_PUBLIC, authorization_grant_type=Application.GRANT_PASSWORD)
     self.request.client = self.application
Exemple #11
0
        def _validate(request, *args, **kwargs):
            core = OAuthLibCore(Server(OAuth2Validator()))
            valid, oauthlib_req = core.verify_request(request, scopes=[])
            if valid:
                # Note, resource_owner is not a very good name for this
                request.resource_owner = oauthlib_req.user
                request.oauth = oauthlib_req
                return view_func(request, *args, **kwargs)

            return build_error_response(401, 'The token authentication failed.')
Exemple #12
0
        def validator(request, *args, **kwargs):
            from oauth2_provider.oauth2_validators import OAuth2Validator
            from oauth2_provider.oauth2_backends import OAuthLibCore
            from oauthlib.oauth2 import Server

            core = OAuthLibCore(Server(OAuth2Validator()))
            valid, oauthlib_req = core.verify_request(request, scopes=scopes)
            if valid:
                request.token = oauthlib_req.access_token
                return f(request, *args, **kwargs)
            return JsonResponseForbidden({
                "error": "invalid token",
                "code": "INVALID_TOKEN"
            })
def test_oidc_endpoint_generation_ssl(oauth2_settings, rf, settings):
    oauth2_settings.OIDC_ISS_ENDPOINT = ""
    django_request = rf.get("/", secure=True)
    # Calling the settings method with a django https request should generate a https url
    oidc_issuer_endpoint = oauth2_settings.oidc_issuer(django_request)
    assert oidc_issuer_endpoint == "https://testserver/o"

    # Should also work with an oauthlib request (via validator)
    core = get_oauthlib_core()
    uri, http_method, body, headers = core._extract_params(django_request)
    request = Request(uri=uri,
                      http_method=http_method,
                      body=body,
                      headers=headers)
    validator = OAuth2Validator()
    oidc_issuer_endpoint = validator.get_oidc_issuer_endpoint(request)
    assert oidc_issuer_endpoint == "https://testserver/o"
 def to_representation(self, instance):
     core = OAuthLibCore()
     uri, http_method, body, headers = core._extract_params(
         self.context['request'])
     headers = {
         **headers,
         'client_id': self.initial_data['client_id'],
         'client_secret': self.initial_data['client_secret'],
     }
     request = Request(uri=uri,
                       http_method=http_method,
                       body=body,
                       headers=headers)
     request.scopes = ['read', 'write']
     request.user = instance.user
     validator = OAuth2Validator()
     validator.authenticate_client(request)
     token = BearerToken(request_validator=validator).create_token(
         request, refresh_token=True, save_token=True)
     return {**token, 'profile': super().to_representation(instance)}
Exemple #15
0
    def __call__(self, request):
        # 正式环境下要检查AccessToken
        if not settings.DEBUG:
            if "account_spider" in request.path:
                authorization = request.META.get("HTTP_AUTHORIZATION", "")
                token = request.GET.get("token", "")
                authorization_session = request.session.get("authorization")
                if token:
                    request.META["HTTP_AUTHORIZATION"] = "Bearer %s" % token
                    request.session['authorization'] = "Bearer %s" % token
                elif authorization:
                    request.session['authorization'] = authorization
                elif authorization_session:
                    request.META["HTTP_AUTHORIZATION"] = authorization_session
                validator = OAuth2Validator()
                core = OAuthLibCore(Server(validator))
                valid, oauthlib_req = core.verify_request(request, scopes=[])
                if not valid:
                    return HttpResponseForbidden()
                request.resource_owner = oauthlib_req.user

        return self.get_response(request)
 def setUp(self):
     self.token = "test_token"
     self.introspection_url = "http://example.com/token/introspection/"
     self.introspection_token = "test_introspection_token"
     self.validator = OAuth2Validator()
 def __init__(self, server=None):
     """
     :params server: An instance of oauthlib.oauth2.Server class
     """
     self.server = server or oauth2.Server(OAuth2Validator())
def test_validate_id_token_app_removed(oauth2_settings, mocker, oidc_tokens):
    oidc_tokens.application.delete()
    validator = OAuth2Validator()
    status = validator.validate_id_token(oidc_tokens.id_token, ["openid"],
                                         mocker.sentinel.request)
    assert status is False
def test_validate_id_token_no_token(oauth2_settings, mocker):
    validator = OAuth2Validator()
    status = validator.validate_id_token("", ["openid"],
                                         mocker.sentinel.request)
    assert status is False