django-oauth-toolkit : Customize authenticate response

2024/11/16 5:23:50

I am new to Django OAuth Toolkit. I want to customize the authenticate response.

My authenticate url configuration on django application is :

url('authenticate/',include('oauth2_provider.urls', namespace='oauth2_provider'))

https://django-oauth-toolkit.readthedocs.io/en/latest/install.html

Now, when i launch this command :

curl -X POST -d 'grant_type=password&username=$username&password=$password'-u "$client_id:$client_secret" http://127.0.0.1:8000/authenticate/token/

I get this response :

{"access_token": "ATiM10L0LNaldJPk12drXCjbhoeDR8","expires_in": 36000,"refresh_token": "II4UBhXhpVDEKWmsUQxDzkj3OMjW1p","scope": "read groups write","token_type": "Bearer"
}

And would like this response :

{"access_token": "ATiM10L0LNaldJPk12drXCjbhoeDR8","expires_in": 36000,"refresh_token": "II4UBhXhpVDEKWmsUQxDzkj3OMjW1p","scope": "read groups write","token_type": "Bearer","member": {"id": 1,"username": "username","email": "[email protected]",....}
}

I just want to override this response for add information of authenticated user. I have read the documentation of django-oauth-toolkit. And i didn't find a solution to my problem...

Answer

I was able to make this change by overwriting the TokenView class in your views.py

from django.http import HttpResponse
from oauth2_provider.views.base import TokenView
from django.utils.decorators import method_decorator
from django.views.decorators.debug import sensitive_post_parameters
from oauth2_provider.models import get_access_token_model, get_application_model
from oauth2_provider.signals import app_authorized
import jsonclass CustomTokenView(TokenView):@method_decorator(sensitive_post_parameters("password"))def post(self, request, *args, **kwargs):url, headers, body, status = self.create_token_response(request)if status == 200:body = json.loads(body)access_token = body.get("access_token")if access_token is not None:token = get_access_token_model().objects.get(token=access_token)app_authorized.send(sender=self, request=request,token=token)body['member'] = {'id': token.user.id, 'username': token.user.username, 'email': token.user.email}body = json.dumps(body) response = HttpResponse(content=body, status=status)for k, v in headers.items():response[k] = vreturn response

In urls.py, just overwrite the token url by pointing to the custom view. This import should come before the include of the django-oauth-toolkit

url(r"authenticate/token/$", CustomTokenView.as_view(), name="token"),
url('authenticate/',include('oauth2_provider.urls', namespace='oauth2_provider'))

The return will now contain the member data

  {"access_token": "YtiH9FGwAf7Cb814EjTKbv3FCpLtag", "expires_in": 36000, "token_type": "Bearer", "scope": "read write groups", "refresh_token": "99TyWmCwELrJvymT8m6Z9EPxGr3PJi", "member": {"id": 1, "username": "admin", "email": "[email protected]"}}
https://en.xdnf.cn/q/71381.html

Related Q&A

Pushing local branch to remote branch

I created new repository in my Github repository.Using the gitpython library Im able to get this repository. Then I create new branch, add new file, commit and try to push to the new branch.Please chec…

Does Pandas, SciPy, or NumPy provide a cumulative standard deviation function?

I have a Pandas series. I need to get sigma_i, which is the standard deviation of a series up to index i. Is there an existing function which efficiently calculates that? I noticed that there are the …

Python: compile into an Unix commandline app

I am not sure if I searched for the wrong terms, but I could not find much on this subject. I am on osx and Id like to compile a commandline python script into a small commandline app, that I can put i…

ModuleNotFoundError in PySpark Worker on rdd.collect()

I am running an Apache Spark program in python, and I am getting an error that I cant understand and cant begin to debug. I have a driver program that defines a function called hound in a file called h…

Sphinx is not able to import anything

I am trying to use sphinx to document a project of mine. I have used autodoc strings within all of my modules and files. I used sphinx-apidoc to automatically generate rst files for my code. So far, so…

Python : why a method from super class not seen?

i am trying to implement my own version of a DailyLogFile from twisted.python.logfile import DailyLogFileclass NDailyLogFile(DailyLogFile):def __init__(self, name, directory, rotateAfterN = 1, defaultM…

Extract features from last hidden layer Pytorch Resnet18

I am implementing an image classifier using the Oxford Pet dataset with the pre-trained Resnet18 CNN. The dataset consists of 37 categories with ~200 images in each of them. Rather than using the final…

Python Graphs: Latex Math rendering of node labels

I am using the following code to create a pygraphviz graph. But is it possible to make it render latex math equations (see Figure 1)? If not, is there an alternative python library that plots similar…

Given general 3D plane equation

Lets say I have a 3D plane equation:ax+by+cz=dHow can I plot this in python matplotlib?I saw some examples using plot_surface, but it accepts x,y,z values as 2D array. I dont understand how can I conv…

Spark-submit fails to import SparkContext

Im running Spark 1.4.1 on my local Mac laptop and am able to use pyspark interactively without any issues. Spark was installed through Homebrew and Im using Anaconda Python. However, as soon as I try…