第一步是使用cookie authentication
in Startup.cs
:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
In the Configure
方法,使用UseAuthentication
方法来调用设置 HttpContext.User 属性的身份验证中间件。调用前先调用UseAuthentication方法UseMvcWithDefaultRoute
or UseMvc
:
app.UseAuthentication();
然后在您的身份验证控制器中,在获取令牌并解码以获取声明后,您应该创建新的ClaimsIdentity
,添加您的声明和登录用户:
if (!User.Identity.IsAuthenticated)
{
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role);
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, YourName));
identity.AddClaim(new Claim(ClaimTypes.Name, YourName));
identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
//Add your custom claims
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties { IsPersistent = true });
}
之后,您可以使用User.Identity.IsAuthenticated
, User.IsInRole("Admin")
and [Authorize(Roles="Admin")]
:
[Authorize(Roles = "Admin")]
public IActionResult About()
{
var result = User.IsInRole("Admin");
return View();
}