class TestOAuthLibCoreBackend(TestCase):

    def setUp(self):
        self.factory = RequestFactory()
        self.oauthlib_core = OAuthLibCore()

    def test_swappable_server_class(self):
        with mock.patch("oauth2_provider.oauth2_backends.oauth2_settings.OAUTH2_SERVER_CLASS"):
            oauthlib_core = OAuthLibCore()
            self.assertTrue(isinstance(oauthlib_core.server, mock.MagicMock))

    def test_form_urlencoded_extract_params(self):
        payload = "grant_type=password&username=john&password=123456"
        request = self.factory.post("/o/token/", payload, content_type="application/x-www-form-urlencoded")

        uri, http_method, body, headers = self.oauthlib_core._extract_params(request)
        self.assertIn("grant_type=password", body)
        self.assertIn("username=john", body)
        self.assertIn("password=123456", body)

    def test_application_json_extract_params(self):
        payload = json.dumps({
            "grant_type": "password",
            "username": "******",
            "password": "******",
        })
        request = self.factory.post("/o/token/", payload, content_type="application/json")

        uri, http_method, body, headers = self.oauthlib_core._extract_params(request)
        self.assertNotIn("grant_type=password", body)
        self.assertNotIn("username=john", body)
        self.assertNotIn("password=123456", body)
class TestOAuthLibCoreBackend(TestCase):

    def setUp(self):
        self.factory = RequestFactory()
        self.oauthlib_core = OAuthLibCore()

    def test_swappable_server_class(self):
        with mock.patch("oauth2_provider.oauth2_backends.oauth2_settings.OAUTH2_SERVER_CLASS"):
            oauthlib_core = OAuthLibCore()
            self.assertTrue(isinstance(oauthlib_core.server, mock.MagicMock))

    def test_form_urlencoded_extract_params(self):
        payload = "grant_type=password&username=john&password=123456"
        request = self.factory.post("/o/token/", payload, content_type="application/x-www-form-urlencoded")

        uri, http_method, body, headers = self.oauthlib_core._extract_params(request)
        self.assertIn("grant_type=password", body)
        self.assertIn("username=john", body)
        self.assertIn("password=123456", body)

    def test_application_json_extract_params(self):
        payload = json.dumps({
            "grant_type": "password",
            "username": "******",
            "password": "******",
        })
        request = self.factory.post("/o/token/", payload, content_type="application/json")

        uri, http_method, body, headers = self.oauthlib_core._extract_params(request)
        self.assertNotIn("grant_type=password", body)
        self.assertNotIn("username=john", body)
        self.assertNotIn("password=123456", body)
Exemple #3
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()
Exemple #4
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 #5
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 _validate(request, *args, **kwargs):
            validator = validator_cls()
            core = OAuthLibCore(server_cls(validator))
            valid, oauthlib_req = core.verify_request(request, scopes=_scopes)
            if valid:
                # here we check if the access to resource is allowed by the token's scope.
                if not allow_resource(oauthlib_req.access_token, request.method, request.path):
                    return HttpResponseForbidden('token has no capability to access the resource')

                request.resource_owner = oauthlib_req.user
                return view_func(request, *args, **kwargs)
            return HttpResponseForbidden('token authentication failed')
Exemple #7
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 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 #9
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 test_swappable_server_class(self):
     with mock.patch("oauth2_provider.oauth2_backends.oauth2_settings.OAUTH2_SERVER_CLASS"):
         oauthlib_core = OAuthLibCore()
         self.assertTrue(isinstance(oauthlib_core.server, mock.MagicMock))
 def setUp(self):
     self.factory = RequestFactory()
     self.oauthlib_core = OAuthLibCore()
Exemple #12
0
    def post(self, request):

        if request.auth is None:
            custom_user = None
            try:
                custom_user = CustomUser.objects.get(
                    email=request.data.get('username'))
            except CustomUser.DoesNotExist:
                return Response(ReturnResponse.Response(
                    1, __name__, "no user", "error").return_json(),
                                status=status.HTTP_400_BAD_REQUEST)
            try:
                with transaction.atomic():
                    custom_user = authenticate(
                        request,
                        username=custom_user.username,
                        password=request.data.get('password'))
                    if custom_user is None:
                        return Response(ReturnResponse.Response(
                            1, __name__, "Failed AuthenticaTion",
                            "error").return_json(),
                                        status=status.HTTP_401_UNAUTHORIZED)
                    login(request, custom_user)
                    uri, http_method, body, headers = self._extract_params(
                        request)
                    data = body
                    params = dict(parse.parse_qsl(data))
                    uri = OAuthLibCore().create_authorization_response(
                        request=request,
                        scopes={
                            "read": "Read Scope",
                            "write": "Write Scope"
                        },
                        credentials={
                            "redirect_uri": params['redirect_uri'],
                            "response_type": params['response_type'],
                            "client_id": params['client_id']
                        },
                        allow=True)

                    params = parse.urlparse(uri[0])
                    params = dict(parse.parse_qsl(params.fragment))
                    return Response(params, status=200)
                    if status_code != 200:
                        raise Exception(
                            json.loads(body).get("error_description", ""))
                    return Response(json.loads(body), status=status_code)
            except Exception as error:
                print("error")
                print(error)
                return Response(ReturnResponse.Response(
                    1, __name__, error, "error").return_json(),
                                status=status.HTTP_400_BAD_REQUEST)

            print("error2")
            return Response(ReturnResponse.Response(1, __name__, "error",
                                                    "error").return_json(),
                            status=status.HTTP_400_BAD_REQUEST)

        print("error3")
        return Response(ReturnResponse.Response(1, __name__, "error",
                                                "error").return_json(),
                        status=status.HTTP_403_FORBIDDEN)
 def setUp(self):
     self.factory = RequestFactory()
     self.oauthlib_core = OAuthLibCore()
Exemple #14
0
 def test_swappable_server_class(self):
     self.oauth2_settings.OAUTH2_SERVER_CLASS = mock.MagicMock
     oauthlib_core = OAuthLibCore()
     self.assertTrue(isinstance(oauthlib_core.server, mock.MagicMock))