Create custom Authorizeattribute
ASP.NET CORE
Allows you to specify the authorization requirements for the operation or controller. Although the early version provides the method, this method has been replaced.
AuthorizeAttribute
Current method: Policies AuthorizeCore
The recommendation method of creating a customized authorized attribute is to use strategies. In the file of the application, you can register a custom strategy and associate them with specific requirements. For example:
Then, in your controller, you can use the attribute specified strategy: Startup.cs
<code class="language-csharp">public void ConfigureServices(IServiceCollection services)
{
services.AddAuthorization(options =>
{
options.AddPolicy("RequireAge18", policy => policy.RequireClaim(MyClaimTypes.Age, "18"));
});
}</code>
Alternative method: IAutHorizationFilter [Authorize]
However, for the simpler scenario, <code class="language-csharp">[Authorize(Policy = "RequireAge18")]
public class MyController : Controller { }</code>
interface provides a method to achieve customized authorization logic. You can define the new attributes of inherit and specify the custom filter:
Then you can use your attributes for operation or controller:
IAuthorizationFilter
Summary TypeFilterAttribute
<code class="language-csharp">public class ClaimRequirementAttribute : TypeFilterAttribute
{
public ClaimRequirementAttribute(string claimType, string claimValue) : base(typeof(ClaimRequirementFilter))
{
Arguments = new object[] { new Claim(claimType, claimValue) };
}
}
public class ClaimRequirementFilter : IAuthorizationFilter
{
readonly Claim _claim;
public ClaimRequirementFilter(Claim claim)
{
_claim = claim;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
var hasClaim = context.HttpContext.User.Claims.Any(c => c.Type == _claim.Type && c.Value == _claim.Value);
if (!hasClaim)
{
context.Result = new ForbidResult();
}
}
}</code>
According to your specific needs, ASP.NET CORE provides two methods to create customized authorization attributes: strategy and interface. Choose the most in line with your application requirements.
The above is the detailed content of How to Create Custom Authorization Attributes in ASP.NET Core Using Policies and IAuthorizationFilter?. For more information, please follow other related articles on the PHP Chinese website!