我已经实现了代码,在这里,我可以使用一个基本的谷歌auth登录。用户可以登录,查看显示电子邮件的页面,并返回到google登录屏幕并选择一个新帐户。
然而,我注意到,几天后,由于某种原因,网站停止要求用户登录,网站将自动登录。在这种状态下,用户也不能注销,而且我仍然可以在使用前面使用的原始方法注销时看到前一个用户的登录。我希望用户在每次加载站点时都选择登录,我希望用户能够在不需要进入匿名模式的情况下注销。
其他一些注意事项:
下面是一个使用新的.NET Core6MVCWebApp的示例。
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 });
}
}
发布于 2022-07-25 22:21:11
我自己也遇到过这个。Google的文档声明,您可以在重定向登录时传递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;
};
});
我希望这能帮到你。
https://stackoverflow.com/questions/72007481
复制相似问题