Aboubacar Traore
Aboubacar Traore

Reputation: 70

Google Authorization Error Error 400: redirect_uri_mismatch

I have a serious issue with my asp.net core web api, the google login works fine on localhost but when publish on the remote server in ElasticBeanstalk it's throws this error. All the authentication process is ok on localhost. Please if someone can help to fix this issue.

Here is the exact same code that i'm using.

`public class AuthController : ControllerBase { const string callbackScheme = "xamarinessentials";

    [HttpGet("{scheme}")]
    public async Task Get([FromRoute]string scheme)
    {
        var auth = await Request.HttpContext.AuthenticateAsync(scheme);

        if (!auth.Succeeded
            || auth?.Principal == null
            || !auth.Principal.Identities.Any(id => id.IsAuthenticated)
            || string.IsNullOrEmpty(auth.Properties.GetTokenValue("access_token")))
        {
            // Not authenticated, challenge
            await Request.HttpContext.ChallengeAsync(scheme);
        }
        else
        {
            var claims = auth.Principal.Identities.FirstOrDefault()?.Claims;
            var email = string.Empty;
            email = claims?.FirstOrDefault(c => c.Type == System.Security.Claims.ClaimTypes.Email)?.Value;

            // Get parameters to send back to the callback
            var qs = new Dictionary<string, string>
            {
                { "access_token", auth.Properties.GetTokenValue("access_token") },
                { "refresh_token", auth.Properties.GetTokenValue("refresh_token") ?? string.Empty },
                { "expires", (auth.Properties.ExpiresUtc?.ToUnixTimeSeconds() ?? -1).ToString() },
                { "email", email }
            };

            // Build the result url
            var url = callbackScheme + "://#" + string.Join(
                "&",
                qs.Where(kvp => !string.IsNullOrEmpty(kvp.Value) && kvp.Value != "-1")
                .Select(kvp => $"{WebUtility.UrlEncode(kvp.Key)}={WebUtility.UrlEncode(kvp.Value)}"));

            // Redirect to final url
            Request.HttpContext.Response.Redirect(url);
        }
    }`

enter image description here enter image description here

Here is the Google auth config in startup.cs or program.cs in .net 6. enter image description here

This is my Google Developper consol enter image description here

Upvotes: 2

Views: 1702

Answers (2)

YourMomIsAHoua
YourMomIsAHoua

Reputation: 71

For anyone who is struggling with this issue, i found out the the key to have everything running ok on a real server, is to make sure that HTTPS is enforced both in your app and on the server.

In your app Program.cs make sure that both the app and Google cookies are transmited over https:

    builder.Services.AddSession(options =>
{
    options.Cookie.SecurePolicy = CookieSecurePolicy.Always;

});


services.AddAuthentication().AddGoogle(googleOptions =>
{
    googleOptions.CorrelationCookie.SecurePolicy = CookieSecurePolicy.Always;

});

The issue with the redirect mismatch was really frustrating one, its seemed that nothing worked until i enforced https

        app.Use((context, next) =>
    {
        context.Request.Scheme = "https";
        return next(context);
    });

These issues usualy happen when you use a reverse proxy server (In my case Apache) Hope that this will help out

Upvotes: 0

Aboubacar Traore
Aboubacar Traore

Reputation: 70

You need to accept the XForwardedProto

In Startup.cs or Program.cs (in .net 6)

public void ConfigureServices(IServiceCollection services)
{
  ...
    services.Configure<ForwardedHeadersOptions>(options =>
    {
        options.ForwardedHeaders = ForwardedHeaders.XForwardedProto;
    });
   ...  
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
 ...
 app.UseForwardedHeaders();
 ...
}

Upvotes: 2

Related Questions