asp.net core中使用cookie身份验证

配置

在 Startup.ConfigureServices 方法中,创建具有 AddAuthentication 和 AddCookie 方法的身份验证中间件服务:

services.AddAuthentication(Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                // Cookie settings
                options.Cookie.HttpOnly = true;
                options.ExpireTimeSpan = TimeSpan.FromMinutes(20);

                options.LoginPath = "/Account/Login";
                options.AccessDeniedPath = "/Account/AccessDenied";
                options.SlidingExpiration = true;
            });

AuthenticationScheme 传递到 AddAuthentication 设置应用程序的默认身份验证方案。 如果有多个 cookie 身份验证实例,并且你想要使用特定方案进行授权,AuthenticationScheme 会很有用。 将 AuthenticationScheme 设置为CookieAuthenticationDefaults。 AuthenticationScheme为方案提供值 "cookie"。 可以提供任何用于区分方案的字符串值。
应用的身份验证方案不同于应用的 cookie 身份验证方案。 如果未向 AddCookie提供 cookie 身份验证方案,则使用 CookieAuthenticationDefaults.AuthenticationScheme ("Cookie")。
默认情况下,身份验证 cookie 的 IsEssential 属性设置为 true。 当站点访问者未同意数据收集时,允许使用身份验证 cookie。 


在 Startup.Configure中,调用 UseAuthentication 和 UseAuthorization 设置 HttpContext.User 属性,并为请求运行授权中间件。 调用 UseEndpoints之前调用 UseAuthentication 和 UseAuthorization 方法:

app.UseCookiePolicy();
app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints
=> {   endpoints.MapControllers();   endpoints.MapRazorPages(); });

登录

若要创建保存用户信息的 cookie,请构造一个 ClaimsPrincipal。 将对用户信息进行序列化并将其存储在 cookie 中。
使用任何所需的 Claim创建 ClaimsIdentity,并调用 SignInAsync 以登录用户:

var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.Email),
new Claim("FullName", user.FullName),
new Claim(ClaimTypes.Role, "Administrator"),
};

var claimsIdentity = new ClaimsIdentity(
claims, CookieAuthenticationDefaults.AuthenticationScheme);

var authProperties = new AuthenticationProperties
{
//AllowRefresh = <bool>,
// Refreshing the authentication session should be allowed.

//ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10),
// The time at which the authentication ticket expires. A 
// value set here overrides the ExpireTimeSpan option of 
// CookieAuthenticationOptions set with AddCookie.

//IsPersistent = true,
// Whether the authentication session is persisted across 
// multiple requests. When used with cookies, controls
// whether the cookie's lifetime is absolute (matching the
// lifetime of the authentication ticket) or session-based.

//IssuedUtc = <DateTimeOffset>,
// The time at which the authentication ticket was issued.

//RedirectUri = <string>
// The full path or absolute URI to be used as an http 
// redirect response value.
};

await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme, 
new ClaimsPrincipal(claimsIdentity), 
authProperties);

SignInAsync 创建加密的 cookie,并将其添加到当前响应中。 如果未指定 AuthenticationScheme,则使用默认方案。
ASP.NET Core 的数据保护系统用于加密。 对于托管在多台计算机上的应用程序、跨应用程序或使用 web 场进行负载平衡,请将数据保护配置为使用相同的密钥环和应用程序标识符。

注销

若要注销当前用户并删除其 cookie,请调用 SignOutAsync:

await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

如果 CookieAuthenticationDefaults.AuthenticationScheme (或 "Cookie")不用作方案(例如 "ContosoCookie"),请提供配置身份验证提供程序时所使用的方案。 否则,将使用默认方案。