jazzband / django-oauth-toolkit

OAuth2 goodies for the Djangonauts!
https://django-oauth-toolkit.readthedocs.io
Other
3.13k stars 792 forks source link

Custom validator not being called #1413

Closed duffn closed 6 months ago

duffn commented 6 months ago

My question is very similar to https://github.com/jazzband/django-oauth-toolkit/issues/1167, but I still don't know the solution.

django-oauth-toolkit 2.3.0 django 4.2.11

I have a custom validator:

class CustomOAuth2Validator(OAuth2Validator):
    def validate_client_id(self, client_id, request, *args, **kwargs):
        print("vaddddddd")
        return self._load_application(client_id, request) is not None

    def validate_scopes(self, client_id, scopes, client, request, *args, **kwargs):
        print("yaaaaal")
        return True

Per the docs, I have added to my settings:

OAUTH2_PROVIDER = {
    "OAUTH2_VALIDATOR_CLASS": "config.oauth2_validators.CustomOAuth2Validator",
    "SCOPES": {"read": "Read scope", "write": "Write scope", "thing": "Another scope"},
    .......
}

My endpoint/viewset

class ThingFeedView(ScopedProtectedResourceView):
    required_scopes = ["thing"]

    def get(self, request: HttpRequest):
        return Response({"message": "thing"})

class ThingFeedViewSet(viewsets.GenericViewSet):
    permission_classes = [permissions.IsAuthenticated]

    @action(methods=["get"], url_path="thjing", detail=False)
    def pro(self, request, *args, **kwargs):
        print("suuuuup")
        return ThingFeedView.as_view()(request)

OAuth authentication seems to work fine, however, my custom validator is not called. There are no print statements.

If I change the class to an invalid one, I do get an error, so it is attempting to load it and I believe the path is correct (I'm also using a similar path for other packages' settings), but it does not get called.

I can even put some print statements in the library itself and see my custom class seemingly being loaded:

<class 'config.oauth2_validators.CustomOAuth2Validator'>
<config.oauth2_validators.CustomOAuth2Validator object at 0x7fe6e9032d90>

However, I don't see the print statements in my custom class itself. What piece am I missing?

duffn commented 6 months ago

This is user error. It is actually working. I was trying with various functions that simply did not get called in my testing flow. Do something like the below and it clearly works.

    def validate_bearer_token(self, token, scopes, request):
        return False