Cookie middleware events

Cookie middleware provides various events that can be overridden by defining the method name through CookieAuthenticationOptions. This is beneficial in terms if you need to add your own logic of setting up a browser cookie or clearing up a browser cookie, validating a cookie, and more.

The following are the events provided in the CookieAuthenticationOptions:

Event Description
RedirectToAccessDenied When an access denied causes a redirect in the cookie middleware.
RedirectToLoginIn When a sign in causes a redirect in the cookie middleware.
RedirectToLogout When a sign out causes a redirect in the cookie middleware.
RedirectToReturnUrl When redirecting to a return URL.
SignedIn When a cookie is created and a user is signed in.
SigningIn When a cookie is created. Claims can be modified and added by overriding this method.
SigningOut To do specific operations during a sign-out operation. For example, clearing up the session and so on.
ValidatePrincipal Called each time when the request is validated. This can be used to verify the user from a database or external source based on the claims. For example, a cookie once set remains in the browser until a user signs out or the cookie expires. This can be used in conditions if we need to verify the user permissions for a specific page and navigate to the access denied page if that permission is not assigned.

Events can be specified as follows, where options are the instance of CookieAuthenticationEvents:

    options.Events = new Microsoft.AspNetCore.Authentication.
Cookies.CookieAuthenticationEvents
{
OnValidatePrincipal = CookieEvents
.ValidateUserPermissions
};

CookieEvents is a custom class that contains a static method named ValidateUserPermissions, which can be specified through the OnValidatePrincipal property.

Here is the code of the CookieEvents class:

    public class CookieEvents 
{
public static async Task ValidateUserPermissions(
CookieValidatePrincipalContext context)
{
bool pathExist = CheckIfPageExist(
context.HttpContext.Request.Path.Value,
context.HttpContext.User.Claims);
if (!pathExist)
{
context.HttpContext.Response.Redirect(
"/Account/AccessDenied");
}

}
}

Once the user is authenticated and the cookie is set, this method will be called every time when the request is made. In the preceding code we are passing the request path to the CheckIfPageExist method that checks if the user has an access to a particular resource and redirects it to the access denied page on a deny case. There are various other scenarios in which this can be overridden, such as if you want to check if the user is still active in the system and sign out in case a user is deactivated.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.28.107