我已经实现了能够使用基本的谷歌身份验证登录的代码。用户可以登录、查看显示电子邮件的页面,然后注销回到 Google 登录屏幕并选择一个新帐户。
但是,我注意到大约几天后,由于某种原因,该网站不再要求用户登录,并且该网站会自动登录。在这种状态下,用户也无法注销,并且在使用上面之前工作的原始方法注销时,我仍然可以看到上一个用户的登录信息。我希望用户在每次加载网站时选择登录名,并且希望用户能够注销而无需进入隐身模式。
其他一些注意事项:
- 即使在隐身模式下,如果用户登录,用户也无法注销,除非在此状态下创建新的隐身窗口。
- 是否有原因导致登录/注销可以运行几天,然后 Google Chrome(以及 Mobile Safari 等其他浏览器)就会变得异常并停止要求用户登录?
- 我还尝试在设置中禁用 Chrome 自动登录,但症状仍然存在。
- 我尝试过切换 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/