ASP.NET Core MVC Google Auth Logout issue

Viewed 216

I have implemented code where I am able to use a basic google auth login. The user is able to login, see the page with their email displayed, and logout back to the google login screen and choose a new account.

However, I've noticed that after a few days or so, for some reason the site stops asking the user to login and the site is automatically logged into. In this state, the user also cannot logout and I can still see the login of the previous user when logging out using the original methods that previously worked above. I want the user to choose the login each time the site loads and I want the user to be able to logout without having to enter incognito mode.

Some other notes:

  1. Even in incognito mode, if the user logs in, the user cannot logout until making a new incognito window in this state.
  2. Is there a reason login/logout works for a few days and then google chrome (and other browsers such as mobile safari) just go rogue and stop asking the user to login?
  3. I've also tried disabling chrome auto sign-in within the settings, the symptoms persist.
  4. I've tried switching around the UseAuthentication() and UseAuthorization() calls and a few other tweaks but maybe I've just got something wrong altogether here.

Below is an example using a new .NET Core 6 MVC Web App.

Program.cs

using Microsoft.AspNetCore.Authentication.Cookies;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

// Using GoogleDefaults.AuthenticationScheme or leaving blank below leads to errors
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie()
    .AddGoogle(options =>
    {
        options.ClientId = "<CLIENT ID FROM GOOGLE CONSOLE>";
        options.ClientSecret = "<SECRET FROM GOOGLE CONSOLE>";
        options.SaveTokens = true;
    });

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();
app.UseAuthentication();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

AccountController.cs

public class AccountController : Controller
{
    [AllowAnonymous]
    public IActionResult Login(string redirectUrl)
    {
        return new ChallengeResult("Google");
    }

    [AllowAnonymous]
    public async Task<IActionResult> Logout()
    {
        await HttpContext.SignOutAsync();

        // Redirect to root so that when logging back in, it takes to home page
        return Redirect("/");
    }
}

HomeController.cs

[Authorize(AuthenticationSchemes = GoogleDefaults.AuthenticationScheme)]
public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }

    public IActionResult Index()
    {
        return View();
    }

    public IActionResult Privacy()
    {
        return View();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}
1 Answers

Just come across this myself. The documentation for Google Identity states that you can pass prompt=consent on redirect to login to force the user to pick an account.

See here: https://developers.google.com/identity/protocols/oauth2/openid-connect#re-consent

Program.cs

.AddGoogle(options =>
{
    options.Events.OnRedirectToAuthorizationEndpoint = context =>
    {
        context.Response.Redirect(context.RedirectUri + "&prompt=consent");
        return Task.CompletedTask;
    };
});

I hope this helps.

Related