I am trying to signup using access token for google. My frontend is next.js with next-auth.js fetching the access_token, refresh_token, etc. I am using python social auth with Django to persist the user information. I use the access_token provided by next-auth to signup the user in Django. How do I make sure that the other response fields like refresh_token, and expires are saved in the Django DB? I can pass the required fields from next-auth to an API in Django but not sure what the expected format is.
https://python-social-auth.readthedocs.io/en/latest/use_cases.html#signup-by-oauth-access-token
@psa('social:complete')
def register_by_access_token(request, backend):
# This view expects an access_token GET parameter, if it's needed,
# request.backend and request.strategy will be loaded with the current
# backend and strategy.
token = request.GET.get('access_token')
user = request.backend.do_auth(token)
if user:
return HttpResponse(json.dumps(get_tokens_for_user(user)))
else:
return HttpResponse('Unauthorized', status=401)
CodePudding user response:
Sounds like you need a table to store these tokens (not sure if you have one already), lets take this model as an example:
class StoredToken(models.Model):
refresh_token = models.CharField()
access_token = models.CharField()
# Maybe you need the related user too?
user = models.ForeignKey(User, on_delete=models.CASCADE)
After you created your table, all you need is to save your data when you have it, from your example:
def get_tokens_for_user(user):
refresh = RefreshToken.for_user(user)
update_last_login(None, user)
StoredToken.objects.create(refresh_token=refresh, access_token=refresh.access_token, user=user)
return {
'refresh': str(refresh),
'access': str(refresh.access_token),
}
You obviously need to do migrations to generate your table, but I assume you have the knowledge to do that. Otherwise refer to the django documentation to create models
CodePudding user response:
I was able to store the refresh token along with other EXTRA_DATA in python social auth by adding response
kwarg. This response
kwarg is nothing but the dictionary containing the extra data.
For example: With Google, response
is the return value of https://developers.google.com/identity/protocols/oauth2/web-server#exchange-authorization-code
@psa
def register_by_access_token(request, backend):
# If it's needed, request.backend and request.strategy will be loaded with the current
# backend and strategy.
response = json.loads(request.body.decode('utf-8'))
user = request.backend.do_auth(response['access_token'], response=response)
if user:
return HttpResponse(json.dumps(get_tokens_for_user(user)))
else:
return HttpResponse('Unauthorized', status=401)