c# - ASP.NET Core MVC Google Auth 注销问题

标签 c# asp.net-mvc asp.net-core authentication

我已经实现了能够使用基本的谷歌身份验证登录的代码。用户可以登录、查看显示电子邮件的页面,然后注销回到 Google 登录屏幕并选择一个新帐户。

但是,我注意到大约几天后,由于某种原因,该网站不再要求用户登录,并且该网站会自动登录。在这种状态下,用户也无法注销,并且在使用上面之前工作的原始方法注销时,我仍然可以看到上一个用户的登录信息。我希望用户在每次加载网站时选择登录名,并且希望用户能够注销而无需进入隐身模式。

其他一些注意事项:

  1. 即使在隐身模式下,如果用户登录,用户也无法注销,除非在此状态下创建新的隐身窗口。
  2. 是否有原因导致登录/注销可以运行几天,然后 Google Chrome(以及 Mobile Safari 等其他浏览器)就会变得异常并停止要求用户登录?
  3. 我还尝试在设置中禁用 Chrome 自动登录,但症状仍然存在。
  4. 我尝试过切换 UseAuthentication() 和 UseAuthorization() 调用以及一些其他调整,但也许我在这里完全出了问题。

下面是使用新的 .NET Core 6 MVC Web 应用程序的示例。

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 });
    }
}

最佳答案

我自己也遇到过这个。 Google Identity 的文档指出,您可以在重定向到登录时传递 prompt=consent 来强制用户选择一个帐户。

请参见此处: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;
    };
});

我希望这会有所帮助。

关于c# - ASP.NET Core MVC Google Auth 注销问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72007481/

相关文章:

asp.net-core - 模型集合上的 ModelBinding

c# - C# 代码可以以编译器(或语言)版本为条件吗?

c# - ASP.NET Identity 2 - 在 foo.com 上登录并在 username.foo.com 上注销时注销不起作用

c# - 如何在字符串中嵌入 Razor 变量?

asp.net-mvc - 如何在 MVC Razor View 中分配和使用变量

c# - 如何在我的新 .Net Core 项目中修复 DbUpdateConcurrencyException?

c# - 为什么不能设置循环算法的索引值?

c# - 为什么这种类型不相等?

c# - 你能覆盖私有(private)虚拟方法吗?

asp.net - 在 .NET Core 2.0 中显示 json 数据的问题