lepture / authlib

The ultimate Python library in building OAuth, OpenID Connect clients and servers. JWS,JWE,JWK,JWA,JWT included.
https://authlib.org/
BSD 3-Clause "New" or "Revised" License
4.45k stars 445 forks source link

request to fix illogical and redundant code in ResourceProtector (solution provided). #603

Open danilovmy opened 8 months ago

danilovmy commented 8 months ago

Everywhere in documentation about ResourceProtector, we can find:

from authlib.integrations.django_oauth2 import ResourceProtector, BearerTokenValidator
from django.http import JsonResponse

require_oauth = ResourceProtector()
require_oauth.register_token_validator(BearerTokenValidator(OAuth2Token))

This example with an error (OAuth2Token is not imported) exists in many sources on the internet and probably in many projects. But I don't understand why it cannot be simply organized like this:

require_oauth = ResourceProtector(token_validator=BearerTokenValidator(OAuth2Token))

I don't offer to remove .register_token_validator() method completely, but i am sure: to add posibility to register token_validator on __init__ can reduce on 50% initializing code of ResourceProtector from Authlib in every project! For example:

class Protector(ResourceProtector):
    def __init__(self, *args, **kwargs):
        validator = kwargs.pop('validator', None)
        super().__init__(*args, **kwargs)
        validator and self.register_token_validator(validator)