218*_*490 2 c# authentication asp.net-mvc asp.net-core
我已经实现了可以使用基本的谷歌身份验证登录的代码。用户可以登录,查看显示电子邮件的页面,然后注销回到谷歌登录屏幕并选择一个新帐户。
但是,我注意到,大约几天后,由于某种原因,该网站不再要求用户登录,并且该网站会自动登录。在这种状态下,用户也无法注销,并且在使用上面之前工作的原始方法注销时,我仍然可以看到上一个用户的登录信息。我希望用户在每次加载网站时选择登录名,并且希望用户能够注销而不必进入隐身模式。
其他一些注意事项:
下面是使用新的 .NET Core 6 MVC Web 应用程序的示例。
程序.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();
Run Code Online (Sandbox Code Playgroud)
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("/");
}
}
Run Code Online (Sandbox Code Playgroud)
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 });
}
}
Run Code Online (Sandbox Code Playgroud)
我自己也遇到过这个。Google Identity 的文档指出,您可以将prompt=consent
重定向传递给登录以强制用户选择帐户。
请参阅此处:https ://developers.google.com/identity/protocols/oauth2/openid-connect#re-consent
程序.cs
.AddGoogle(options =>
{
options.Events.OnRedirectToAuthorizationEndpoint = context =>
{
context.Response.Redirect(context.RedirectUri + "&prompt=consent");
return Task.CompletedTask;
};
});
Run Code Online (Sandbox Code Playgroud)
我希望这有帮助。
归档时间: |
|
查看次数: |
1167 次 |
最近记录: |