Tivix / django-rest-auth

This app makes it extremely easy to build Django powered SPA's (Single Page App) or Mobile apps exposing all registration and authentication related functionality as CBV's (Class Base View) and REST (JSON)
www.tivix.com
MIT License
2.4k stars 663 forks source link

Does this support google authentication with react? #626

Closed SanjivG10 closed 3 years ago

SanjivG10 commented 3 years ago

I am using react google login. How can I handle authentication with standard user (not custom) from django all-auth with react front-end. Is there any api-endpoint for google authentication from react front-end?

paulkuhle commented 3 years ago

You have to create views for your social login endpoints. For common OAuth providers like Google and Facebook, this is fairly simple. Just add a class-based view inheriting from SocialLoginView and tell it to use the GoogleOAuth2Adapter.

# views.py
from rest_auth.registration.views import SocialLoginView
from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter

class GoogleLogin(SocialLoginView):
    """allauth social login view for Google"""
    adapter_class = GoogleOAuth2Adapter

Then you simply need to enable the endpoint:

# urls.py
from users.views import GoogleLogin
urlpatterns = [
   # ...
   url(r'^rest-auth/google/$', GoogleLogin.as_view(), name='google_login'),
   #  ...

The onSuccess method of your GoogleLogin component in React has to make a post request to that endpoint:

    Axios
      .post(`${process.env.REACT_APP_DJANGO_HOST}/rest-auth/google/`, {
        access_token,
        code,
      })
     .then((response) => {
        const token = res.data.key;
        // save token in state etc.
     })

The tokens that you have to send are response.accessToken and response.tokenId (of your component's response object).

djb4ai commented 3 years ago

@SanjivG10 Did this work? The DRF endpoint asks for access_token and code, I am just confused which is what from the response I got from Google.

SanjivG10 commented 3 years ago

@adhibhuta I think it should work. You get response from the Google and then try to get the access_key from the object and send the post request. I haven't checked it myself though

colin-byrne-1 commented 3 years ago

I'll play around with it shortly...

SanjivG10 commented 3 years ago

it works. tested.

AREEG94FAHAD commented 3 years ago

I send the access token but i dont know what should i send in case of code🤔 @paulkuhle