Search code examples
asp.netoauthgoogle-plusgoogle-oauthgoogle-signin

Why google login redirect back to site with hashtag - can it be avoided


I didn't succeeded to find any relevant answer to this so I must ask :)
I implemented google plus login to my site. With a few workarounds it work fine but...
When I am redirected back to my site from google I am returned to the following URL:

http://localhost/mysite/west/Default.aspx#state=/profile&access_token=ya29.qQDrtcVtgOEbS86Bg10puFG3dksJz74BlrEGulHldlJW2o5qQ6g7ilF17zQsm8iMLG0C82PQyp2Z-g&token_type=Bearer&expires_in=3600

Because of this parameter here #state=/profile& I first have to read URL in javascript on load,
remove this part to fix URL and then do this:

var url = "Default.aspx?" + queryString;
                window.location = url; 

And then I can continue to read query string normally in code.
I don't like this because when I do this I make two postback on page and I want to avoid this if possible.
Is this redirect url must have this or this can be avoided?

Redirect to google:

string url = "https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email&state=%2Fprofile&redirect_uri="+this.Return_url+"&response_type=token&client_id=" + this.Client_ID;

        Response.Redirect(url);

When I get back to my site:

if (this.Request.QueryString["access_token"] != null)
            {
                String URI = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + Request.QueryString["access_token"].ToString();

                WebClient webClient = new WebClient();
                Stream stream = webClient.OpenRead(URI);

Solution

  • Change response_type=token to response_type=code. The callback URL will then have a code query parameter which is accessible server side instead of a fragment. You will then have to implement step 4 to exchange the code for an access_token.