Search code examples
asp.netasp.net-coreoauth-2.0oauth

ASP.Net Core - OAuth token endpoint failure: Status: BadRequest


When using ASP.Net Core's authentication for Google, I'm performing the following scenario:

  1. Click to login via Google.
  2. Log into Google successfully. At this point I am returned back to my application and I am able to move on my with process. The user claims were returned as expected.
  3. Immediately go back to step 1 and try to login via Google again with the same account. If prompted at Google, select the same account/enter the credentials again.
  4. At this point I now receive the below error.

If I wait a period of time, perhaps 30 minutes, if I start at step 1 again, I don't encounter the issue until I again reach step 4. If I restart my IIS ApplicationPool for my Core project, I can follow the above scenario where step 1 works, but then step 4 shows the issue.

I have searched what feels like endlessly online to no avail. Does anyone have anything they can suggest? Why would this work the first time, and then fail on second, third attempts?

I'm receiving the below error when following the scenario above on my Google Pixel 3 XL phone:

System.Exception: SocialLoginController|Error|OAuth token endpoint failure: Status: BadRequest;Headers: Vary: X-Origin, Referer, Origin,Accept-Encoding Date: Sun, 03 Mar 2019 09:35:45 GMT Server: ESF Cache-Control: private X-XSS-Protection: 1; mode=block X-Frame-Options: SAMEORIGIN X-Content-Type-Options: nosniff Alt-Svc: quic=":443"; ma=2592000; v="44,43,39" Accept-Ranges: none Transfer-Encoding: chunked ;Body: { "error": "invalid_grant",
"error_description": "Bad Request" };

The code in my Startup.cs class for Google's authentication is as follows:

        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        })
        .AddCookie(options =>
        {
            options.LoginPath = "/login";
            options.LogoutPath = "/signout";
        });

services.AddAuthentication().AddGoogle(socialProvider.ProviderName, o =>
{
    o.ClientId = [REMOVED]
    o.ClientSecret = [REMOVED]
    o.UserInformationEndpoint = "https://www.googleapis.com/oauth2/v2/userinfo";
    o.ClaimActions.Clear();
    o.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id");
    o.ClaimActions.MapJsonKey(ClaimTypes.Name, "name");
    o.ClaimActions.MapJsonKey(ClaimTypes.GivenName, "given_name");
    o.ClaimActions.MapJsonKey(ClaimTypes.Surname, "family_name");
    o.ClaimActions.MapJsonKey("urn:google:profile", "link");
    o.ClaimActions.MapJsonKey(ClaimTypes.Email, "email");
    o.CallbackPath = string.Format("/signin-{0}", socialProvider.ProviderName.ToLower());
    o.SaveTokens = true;
    o.Events.OnRemoteFailure = ctx =>
    {
        string message = UrlEncoder.Default.Encode(ctx.Failure.Message);
        if (!string.IsNullOrEmpty(message) && message.Length > 1500)
        {
            message = message.Substring(0, 1499);
        }
        ctx.Response.Redirect(errorRedirectUrl + message);
        ctx.HandleResponse();
        return Task.FromResult(0);
    };
});


services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

Please also see the image below that shows the error when I have enabled "UseDeveloperExceptionPage".

The error shown when UseDeveloperExceptionPage is enabled.

FYI, I am completely unable to replicate the issue on my iPhone and my Desktop PC - I never receive the issue and I can make as many login attempts as I want, the issue never seems to arise on these devices.

I'm lost!


Solution

  • I was able to identify my issue here which turns out to be unique to any other answer I found with the same error I experienced above.

    Issue: On my Pixel device, I have an application (My-App) that runs against the same domain that I was accessing in my Chrome browser. When clicking to login via Google, I remember it asked me if I wanted to 'Open in Chrome' or 'Open in My-App', and I always selected 'Open in Chrome'.

    I uninstalled My-App, and now I am unable to replicate the issue. The issue is gone. I tried the scenario many times to no avail, every time it worked! When I re-installed My-App, the issue came back.

    Fix: the problem that I need to resolve is running my Core project on a different domain other than the domain My-App is running, so there won't be a confusion on the device about whether Chrome should open or My-App should open. Hopefully that will be my fix!

    Thanks for reading.