Claims transformation

Every cookie has an expiry time and the default cookie expiration time in ASP.NET Identity Core is 30 minutes, which is configurable. Claims transformation is a valuable feature that allows developers to add or update claims on every request. For example, if at a particular time we don't want a user to access a resource. We can add a piece of information through claims transformation and validate it through the Authorize attribute in our MVC or Web API controller or action level.

Let's go through an example in which we will add the AllowSecure claim that will be validated when the user accesses the AdminController. The claims transformation has to be added in the HTTP pipeline in the Startup class. Add the following code in the Configure method of the Startup class:

    bool isAllowed = GetUserAllowedBit(); 
if (isAllowed)
{
app.UseClaimsTransformation(user =>
{
user.Context.User.Identities.First().AddClaim(new
Claim("AllowSecure", System.DateTime.Now.ToString()));
return Task.FromResult(user.Principal);
});
}else
{
app.UseClaimsTransformation(user =>
{
if (user.Context.User.Identities.First()
.FindFirst("AllowSecure") != null)
{
user.Context.User.Identities.First()
.RemoveClaim(new Claim("AllowSecure",
System.DateTime.Now.ToString()));
}
return Task.FromResult(user.Principal);
});
}

In the preceding code, we have called our custom GetUserAllowedBit method that returns the Boolean value if the user is allowed or not. If the user is allowed, the claim will be added through the claims transformation; otherwise it will be removed from the user's claims.

Before annotating our Controller with the Authorize attribute, we will set up the policy and specify AllowSecure claim to be required for any user accessing that resource which is protected with this policy.

To understand the policy, please refer to the following authorization techniques. The following code will register the policy in the pipeline:

    services.AddAuthorization(options => 
{
options.AddPolicy("SecureAccess", policy =>
policy.RequireClaim("AllowSecure"));
});

Our AdminController can be protected by just adding the Authorize attribute and reading this claim, as follows:

    [Authorize(Policy ="SecureAccess")] 
public class AdminController : Controller
{
}
..................Content has been hidden....................

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