If you want to use your own data store and login controls to authenticate a user, Cookie middleware is the best choice. Cookie middleware serializes the user principal into an encrypted cookie and it uses that cookie to validate users on every request. The user principal can be retrieved by calling the HttpContext.User property.
Cookie middleware can be used by adding a NuGet package named Microsoft.AspNetCore.Authentication.Cookies and the following code snippet in the Configure method in the Startup class:
CookieAuthenticationOptions options = new
CookieAuthenticationOptions();
options.AuthenticationScheme = "CookiesMiddlewareAuth";
options.LoginPath = "/Account/Login";
options.AccessDeniedPath = "/Account/AccessDenied";
options.AutomaticAuthenticate = true;
options.AutomaticChallenge = true;
app.UseCookieAuthentication(options);
The following table shows a description of few properties that CookieAuthenticationOptions provides:
Property | Description |
AuthenticationScheme | Name of the middleware or by which the middleware is known. |
LoginPath | Relative path to the login page, to which the request will be redirected when an unauthenticated user accesses it. |
AccessDeniedPath | Relative path to the page that shows that the user does not have access rights to a particular resource or page. |
AutomaticAuthenticate | This flag indicates that on every request middleware should run and validate the request. It also reconstructs the principal it created earlier. |
AutomaticChallenge | This flag indicates that the application should redirect the user to the login page or access denied page if the user is not authenticated. |
CookieDomain | Determines the domain used to create the cookie. |
CookieHttpOnly | Determines if the browser should allow the cookie to be accessed by JavaScript. |
CookiePath | Determines the path used to create the cookie. Default value is '/' for the highest browser compatibility. |
CookieSecure | Determines if the cookie is only allowed to be transmitted on HTTPS requests. The default setting is that, if the page using the calling sign in process is using HTTPS, it will default to HTTPS and this bit can be used in the scenario if a sign-in page, or the portions of a page, is using HTTP. |
ExpireTimeSpan | Expiry time to which the cookie will remain valid. |
SlidingExpiration | This can be set to True to instruct the middleware to issue the new cookie with a new expiry time when it reaches half way through the expiration window. |
Cookies can be created by calling the SignInAsync method of AuthenticationManager. The following is the Login (HTTP POST) method that can be called when the user logs in through the Web application:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public IActionResult Login(LoginViewModel model,
string returnUrl = null)
{
var claim = new Claim[]
{
new Claim("sub","123456789"),
new Claim("name","ovaismehboob"),
new Claim("email","[email protected]"),
new Claim("twitter","ovaismehboob"),
new Claim("role", "Admin"),
new Claim("role", "User")
};
ClaimsIdentity claimIdentity = new ClaimsIdentity(
claim, "CookiesAuth");
HttpContext.Authentication.SignInAsync("CookiesAuth",
new System.Security.Claims.ClaimsPrincipal(claimIdentity));
return Redirect(returnUrl);
}
HttpContext.Authentication.SignInAsync(
"CookiesMiddlewareAuth", new
System.Security.Claims.ClaimsPrincipal(claimIdentity));
The first parameter takes the authentication scheme that uses the cookie middleware setup on the Configure method and it uses that for authentication. Claims can be defined by initializing a new Claim instance and specifying the key values pair, which can be added to the claim array as shown previously.
SignInAsync uses the claims passed through the claims identity and sets the cookie. Claims can be retrieved by calling User.Claims, as follows:
<d1>
@foreach (var claim in User.Claims)
{
<dt>@claim.Type</dt>
<dt>@claim.v</dt>
}
</d1>
A sign-out operation, on the other hand, can remove the cookie from the browser and sign out the user. A signing-out operation can be done by writing the following code:
HttpContext.Authentication.SignOutAsync("CookiesMiddlewareAuth");
This method also takes the authentication scheme. So, if multiple middleware are set up, you can sign out the user for a specific authentication scheme, which clears up the cookie from the browser.