jazzband / django-oauth-toolkit

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

Accessing client/application from request #1185

Closed femesq closed 1 year ago

femesq commented 2 years ago

Debugging some OAuth-authenticated request, I noticed that it passes by this line: https://github.com/jazzband/django-oauth-toolkit/blob/492a867499b50f348c28db4ef3e429e8f46dc412/oauth2_provider/oauth2_validators.py#L426

Although I can read request.user inside my "protected" views, the client attribute is not available on request.

I'd like to log some actions, registering the application the user authorized to make these actions.... Is it possible?

JordiNeil commented 2 years ago

Well, not sure it's the best way but I think you can do something like this

from oauth2_provider.models import AccessToken

token_header = request.META['HTTP_AUTHORIZATION']
code = re.search('(?<=Bearer ).*', token_header).group(0)
client = AccessToken.objects.get(token=code).application
dopry commented 1 year ago

@femesq , This might be a nice middleware addition. Care to create a PR?

femesq commented 1 year ago

Would be very happy to contribute to this... Will start studying how middleware works and work on this PR soon...

jhnbyrn commented 1 year ago

I submitted a PR for this. I added it to the existing middleware but it could easily be a separate optional middleware to avoid the db query for those who don't need the access token.

n2ygk commented 1 year ago

I submitted a PR for this. I added it to the existing middleware but it could easily be a separate optional middleware to avoid the db query for those who don't need the access token.

It seems you should make it a separate option, especially since it would otherwise add a DB query to all the current users who don't need the access token.