'How can I get 'sign in with Google' to work using 'dj_rest_auth'?
I'm trying to implement Google sign in using DRF
and dj_rest_auth
.
I've set up 'django-allauth' with Google as provider and the sign in process works in the web browser.
I need to connect an android app with my backend. I've created API endpoints which will require authentication.
According to the docs, code
is required in order to complete authentication and receive the token.
After doing some research, I found that code
required by dj_rest_auth
can be obtained by visiting:
https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=<YOUR CALLBACK URL>&prompt=consent&response_type=code&client_id=<YOUR CLIENT ID>&scope=openid%20email&access_type=offline
However, even after passing code
returned in the query param (after decoding from URL format), the following error is shown:
Error retrieving access token: b'{\n "error": "invalid_grant",\n "error_description": "Bad Request"\n}'
To see if I can log in with a recent access
token, I signed in with my Google account from the homepage , copied the access
token from the admin section and submitted it to the endpoint http://localhost:8000/dj-rest-auth/google/
. I was able to receive the auth token generated by dj_rest_auth
.
I need help in getting the auth token by providing code
in the post request.
My code:
# urls.py
...
path('dj-rest-auth/', include('dj_rest_auth.urls')),
path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')),
path('dj-rest-auth/google/', home.GoogleLogin.as_view(), name='google_login'),
...
# views.py
from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
from allauth.socialaccount.providers.oauth2.client import OAuth2Client
from dj_rest_auth.registration.views import SocialLoginView
class GoogleLogin(SocialLoginView):
adapter_class = GoogleOAuth2Adapter
callback_url = 'http://localhost:8000/accounts/google/login/callback/'
client_class = OAuth2Client
...
References:
Google Social Authentication with dj-rest-auth #220
Minimal example for SPA implementation of social login #147
Please help me.
Solution 1:[1]
Did you create your authentication keys on Google Cloud and add them in settings.py ?
It looks like that for me in settings :
SOCIALACCOUNT_PROVIDERS = {
"google": {
# For each OAuth based provider, either add a ``SocialApp``
# (``socialaccount`` app) containing the required client
# credentials, or list them here:
"APP": {
"client_id": os.environ.get("GOOGLE_CLIENT_ID"),
"secret": os.environ.get("GOOGLE_SECRET_KEY"),
"key": ""
},
# These are provider-specific settings that can only be
# listed here:
"SCOPE": [
"profile",
"email",
],
"AUTH_PARAMS": {
"access_type": "online",
}
}}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Grum |