在ASP.Net Core中,可以使用基于弹出式认证来实现用户认证。下面是一个基本示例:
1.在Startup.cs文件的ConfigureServices方法中添加以下代码:
services.AddAuthentication(options =>
{
options.DefaultScheme = "CookieAuthentication";
options.DefaultChallengeScheme = "CustomScheme";
})
.AddCookie("CookieAuthentication", options =>
{
options.LoginPath = "/Users/Login";
})
.AddOAuth("CustomScheme", options =>
{
options.ClientId = "
options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id");
options.ClaimActions.MapJsonKey(ClaimTypes.Name, "username");
options.ClaimActions.MapJsonKey(ClaimTypes.Email, "email");
});
2.在Startup.cs文件的Configure方法中添加以下代码:
app.UseAuthentication();
3.在控制器中添加以下代码,以在用户单击“登录”按钮时触发基于弹出式认证的流程:
[AllowAnonymous] public IActionResult Login(string returnUrl = "/") { var redirectUrl = Url.Action("Callback", "OAuth", new { ReturnUrl = returnUrl }); var properties = signInManager.ConfigureExternalAuthenticationProperties("CustomScheme", redirectUrl);
return Challenge(properties, "CustomScheme");
}
4.在控制器中添加以下代码,以在用户输入凭据并授权后处理回调:
public async Task
if (result.Succeeded)
{
return Redirect(returnUrl);
}
var info = await signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return RedirectToAction("Login");
}
var user = new ApplicationUser
{
UserName = info.Principal.FindFirstValue(ClaimTypes.Name),
Email = info