I'm currently implementing social login with dj-rest-auth with a custom provider. I have went through plenty of sites but most tutorials/resources don't show how to implement the frontend, so I'm unsure how to implement it. The frontend can only use vanilla js and is a SPA.
My current idea/testing is with a href=127.0.0.1/api/auth/callback which will run the function callback. If a code is not return it'll redirect to the authorize url to obtain one and proceed to be redirected back to the same function to start login. After logging in then redirect to homepage with all relevant cookies.
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": [
"rest_framework.authentication.TokenAuthentication",
'rest_framework.authentication.SessionAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
}
Provider login api (http://127.0.0.1:8000/api/auth/provider/)
auth/views.py
redirect_uri = 'http://127.0.0.1:8000/api/auth/callback/'
def callback(request):
if 'code' in request.GET is None:
socialapp = SocialApp.objects.get(name='provider')
authorize_url = (f'{settings.OAUTH_SERVER_BASEURL}/oauth/authorize'
'?client_id=' + socialapp.client_id +
'&redirect_uri=' + quote(redirect_uri, safe='') +
'&response_type=code')
return redirect(authorize_url)
if 'code' in request.GET:
socialapp = SocialApp.objects.get(name='NAME')
code = request.GET['code']
context = {}
context['grant_type'] = 'authorization_code'
context['client_id'] = socialapp.client_id
context['client_secret'] = socialapp.secret
context['code'] = code
context['redirect_uri'] = 'http://127.0.0.1:8000/api/auth/callback/'
try:
token_response = requests.post('https://provider-api-link/oauth/token', json=context)
data = token_response.json() # access-token is inside
if 'error_description' in data:
print("error_description_post_code:", data)
social_login_response = requests.post('http://127.0.0.1:8000/api/auth/provider/', json=data)
response = HttpResponseRedirect('/')
response.set_cookie("Authorization", 'Token {}'.format(data["key"]), httponly=True)
return response
Now the issue is the returned response have the Authorization cookies but sessionid and other cookies is in social_login_response instead. How do I have a redirect to my homepage with the Authorization Token, seesionid and other relevant cookies?
I have tried going through the cookies in token_response.cookies but am unsure if this is the correct way to handle social login using this package. Any solution or reference would be much appreciated.