To configure
In the Startup.ConfigureServices method, create an authentication middleware service with the AddAuthentication and AddCookie methods:
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; });
Authentication Schemes are passed to AddAuthentication to set the default authentication scheme for the application.AuthenticationSchemes can be useful if you have multiple instances of cookie authentication and you want to authorize with a specific scheme.Set AuthenticationSchemes to CookieAuthenticationDefaults.AuthenticationScheme provides the value "cookie" for the scheme.Any string value can be provided to distinguish the schema.
The authentication scheme applied is different from the cookie authentication scheme applied.If no cookie authentication scheme is provided to AddCookie, use CookieAuthenticationDefaults.AuthenticationScheme ("Cookie").
By default, the IsEssential property of the authentication cookie is set to true.Authentication cookies are allowed when site visitors do not agree to data collection.(
In Startup.Configure, call UseAuthentication and UseAuthorizationto set the HttpContext.User property and run the authorization middleware for the request.Call the UseAuthentication and UseAuthorizationmethods before calling UseEndpoints:
app.UseCookiePolicy();
app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapRazorPages(); });
Sign in
To create a cookie that holds user information, construct a ClaimsPrincipal.User information will be serialized and stored in cookies.
Create ClaimsIdentity with any required Claim and call SignInAsync to log in to the user:
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 creates an encrypted cookie and adds it to the current response.If AuthenticationScheme is not specified, the default scheme is used.
ASP.NET Core's data protection system is used for encryption.For applications hosted on multiple computers, across applications, or using a web farm for load balancing, configure data protection to use the same Keyring and application identifier.
Cancellation
To log off the current user and delete its cookie s, call SignOutAsync:
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
If the CookieAuthenticationDefaults.AuthenticationScheme (or "Cookie") is not used as a scheme (for example, "ContosoCookie"), provide the scheme used to configure the authentication provider.Otherwise, the default scheme will be used.