10

I'm implementing an auth system with django and react. The two app run respectively on port 8000, 3000. I have implemented the authentication system using the Djoser package. This package uses some dependencies social_core and social_django. Everything seems to be configured ok. I click on login google button...I'm redirected to the google login page and then back to my front-end react app at port 3000 with the state and code parameters on the url.

At this point I'm posting those parameters to the backend. The backend trying to validate the state checking if the state key is present in the session storage using the code below from (social_core/backends/oauth.py)

def validate_state(self):
        """Validate state value. Raises exception on error, returns state
        value if valid."""
        if not self.STATE_PARAMETER and not self.REDIRECT_STATE:
            return None
        state = self.get_session_state()
        request_state = self.get_request_state()
        if not request_state:
            raise AuthMissingParameter(self, 'state')
        elif not state:
            raise AuthStateMissing(self, 'state')
        elif not constant_time_compare(request_state, state):
            raise AuthStateForbidden(self)
        else:
            return state

At this point for some reasons the state session key is not there..and I receive an error saying that state cannot be found in session data ( error below )

{"error":["State could not be found in server-side session data."],"status_code":400}

I recap all the action I do:

  1. Front-end request to backend to generate given the provider google-oauth2 a redirect url. With this action the url is generated also the state key is stored on session with a specific value ( google-oauth2_state ).
  2. Front-end receive the url and redirect to google auth page.
  3. Authentication with google and redirection back to the front-end with a state and code parameters on the url.
  4. Front-end get the data form url and post data to back-end to verify that the state received is equal to the generated on the point (1).

For some reasons the state code is not persisted... Any ideas and help will be really appreciated.

Thanks to all.

caot
  • 3,066
  • 35
  • 37
LucaT
  • 333
  • 5
  • 13
  • 1
    If you post the demo code, it helps figure out the issue. – caot May 01 '21 at 01:13
  • Did you solve this issue? happening to me also! But in my case having different URL for server and client so I guess session storing is causing issue but not sure how to fix it! Any help appericiated. – Ishika Jain May 24 '21 at 11:36
  • I wonder if this can be solved using Nginx, as the author did here: https://medium.com/swlh/django-rest-framework-and-spa-session-authentication-with-docker-and-nginx-aa64871f29cd – Saber Oct 03 '21 at 14:24
  • I had React front-end running on localhost:3000 and backend running on 8000. This happened when session data was not being sent to localhost:8000. Unfortunately, I still don't know how to send session data from localhost:3000 to localhost:8000. So for time being, I build the react front-end using `npm run build` and used `collectstatic` command in Django. Then ran the front-end from the same port (localhost:8000). Now the session data was being sent automatically and everything works perfectly for me. – Art Jan 22 '22 at 06:34

4 Answers4

3

ok so this is a common problem while you are working with social auth. I had the same problem for so many times.

The flow:

  1. make a request to http://127.0.0.1:8000/auth/o/google-oauth2/?redirect_uri=http://localhost:3000/ (example)

  2. you will get a authorization_url. if you notice in this authorization_url there is a state presented . this is the 'state of server side'.

  3. now you need to click the authorization_url link.Then you will get the google auth page.After that you will be redirect to your redirect url with a state and a code. Remember this state should be the same state as the server side state .(2)

  4. make post req to http://127.0.0.1:8000/auth/o/google-oauth2/?state=''&code=''. if your states are not the same then you will get some issue.

everytime you wanna login , you need to make a request to http://127.0.0.1:8000/auth/o/google-oauth2/?redirect_uri=http://localhost:3000/ and then to http://127.0.0.1:8000/auth/o/google-oauth2/?state=''&code='' thus you will get the same state.

Rifat Rahman
  • 153
  • 1
  • 5
  • Could you post a codepen of this? The explained way in the docs is to make the post-request from the frontend using the state & code, however this results in the error mentioned above because session ids or some other explanation does not match. – Thorvald Sep 22 '21 at 23:32
  • This is not working. – Khris Vandal Feb 25 '23 at 22:49
1

Without necessary detailed information, I can only tell 2 possible reasons:

  1. You overrode backend with improper session operations(or the user was logged out before auth was finished).
  2. Front-end used incorrect state parameter

You could test social login without front-end, let's say if you're trying to sign in with Google:

  1. Enter the social login URL in browser, like domain.com:8000/login/google-oauth2/
  2. Authorize
  3. See if the page redirected to your default login page correctly

If yes, then probably you need to check your front-end code, and if no, then check your backend code.

At the end, if you're not so sensitive to the potential risk, you could also override GoogleOAuth2 class as following to disable state check:

from social_core.backends import google

class GoogleOAuth2(google.GoogleOAuth2):
    STATE_PARAMETER = False
YKL
  • 542
  • 2
  • 9
1

Finally, I've reached a point where everything is functioning flawlessly, both on the local environment and in production. The core issue turned out to be related to cookies and sessions. The correct solution was to trick the backend server into perceiving the request as if it were coming from "localhost:8000" instead of "localhost:3000". This entails ensuring that the backend domain remains consistent.

To achieve this, there are two feasible approaches:

  1. Serve Frontend Build from the Server: The server should host the compiled version of the frontend. By doing this, the frontend will always share the same domain as the backend.

  2. Django View with Google Auth Logic: Implement a simple Django view and associate an empty template with it. This template should solely contain a script tag incorporating the necessary logic to manage Google authentication. The process involves the following steps:

    • When a user clicks on "Sign in with Google," they are directed to this view.
    • The view manages the authentication process, and upon completion, it retrieves the access token.
    • The access token is then passed to the frontend via URL parameters.

In my case, I opted for the second approach, as it suited my requirements better. The procedure involves creating a basic view and linking it to a template. This way, when a user selects "Sign in with Google," the corresponding view is triggered. Subsequently, the view takes over the authentication process. Once the access token is obtained, it is transferred to the specified URL.

  • https://drive.google.com/file/d/17bTCCN8-UDRCfIbAPpVyJyIQKVqFdOeO/view?usp=sharing if someone doesn't understand the above explanation, I made a video explaining how you can sort out this problem. Thanks – abdullah zulfiqar Aug 15 '22 at 12:06
0

I think you may need some changes in you authorizing flow in step NO.3 and 4.

3.Authentication with google and redirection back to the front-end with a state and code parameters on the url.
4.Front-end get the data form url and post data to back-end to verify that the state received is equal to the generated on the point (1).

maybe you should redirect back to server side after google's authorization.

then at the server side, do the check! validate the state and code (maybe do more things).

then let server redirect to the front-end site you wanted to before.

for some reason, redirect to front-end directly will miss the param.. :-)

tomy0608
  • 317
  • 1
  • 9
  • Could you try to explain using a codepen or some code? The docs very clearly state that the general way to do this is to make the post request from the front end, but since the session id's don't match / are never added, or similar, the request fails. – Thorvald Sep 22 '21 at 23:34