phpgoogle-oauthfacebook-authenticationsocialauth

How to redirect to last link after login from google in php?


I am trying to redirect the user to the last link after login through Gmail or Facebook.

Here are the four things I tried without success.

1) Using $_SERVER['HTTP_REFERER'] But it redirects me back to Gmail instead of the last link on my site.

2) Using $_SESSION - I try to store last url in session before login but after login I don't get its value as session is empty.

3) Using cookies - I also try using cookies but it is also not working

4) I try to send the last url as $_GET parameter in redirect url but doing that stops google login as that url does not match the url stored in google apps.

Is there any other way to achieve this?


Solution

  • I can't see why using cookies wouldn't work. Before redirecting the user to the Authorization Server, store the current URL in a cookie. When the AS redirects the user back to the redirect_uri, that page does another redirect to the URL stored in the cookie.

    But I like the version where you include the "last page URL" in the request better (the 4th element on your list). Since Google apparently doesn't allow wildcards in their OAuth configuration, you can use the state parameter instead. From RFC 6749 - The OAuth 2.0 Authorization Framework:

    state
         RECOMMENDED.  An opaque value used by the client to maintain
         state between the request and callback.  The authorization
         server includes this value when redirecting the user-agent back
         to the client.  The parameter SHOULD be used for preventing
         cross-site request forgery as described in Section 10.12.
    

    When you build your redirect URL, you just set the state parameter like so:

    https://accounts.google.com/o/oauth2/v2/auth
        ?client_id=MY_CLIENT_ID
        &redirect_uri=http://example.com/oauth-redirect_uri
        &scope=REQUESTED_SCOPES
        &state=http://example.com/last-page-the-user-loaded
    

    Depending on your OAuth flow, the Authorization server will redirect the user to an URL that looks somewhat like this upon successful authorization:

    http://example.com/oauth-redirect_uri
        ?code=CODE
        &state=http://example.com/last-page-the-user-loaded
    

    Your server can then process the state parameter and redirect the user accordingly.