Home > Backend Development > C++ > How to Implement Custom Authorization in ASP.NET Core Using Claims?

How to Implement Custom Authorization in ASP.NET Core Using Claims?

Mary-Kate Olsen
Release: 2025-02-01 18:16:10
Original
336 people have browsed it

How to Implement Custom Authorization in ASP.NET Core Using Claims?

Use a statement in ASP.NET CORE to achieve customized authorization attributes

Background

ASP.NET CORE

provides a convenient way to operate based on declaration. However, in the previous version, you can rewrite

to achieve customized authorization logic. This method no longer exists in AuthorizeAttribute. bool AuthorizeCore(HttpContextBase httpContext) AuthorizeAttribute The current method of using strategy

ASP.NET CORE team recommends using strategies for customized authorization. The following is the process:

Define strategy in :
  1. Startup.cs

    Add attribute to your operation or controller:
     options.AddPolicy("YourPolicyName", policy => policy.RequireClaim(...));
    Copy after login
  2. [Authorize] Using the customized authorization attributes of the statement

     [Authorize(Policy = "YourPolicyName")]
     public IActionResult Action(...)
    Copy after login
    If the strategy -based method is not applicable, you can use the
  3. interface to create a custom
:

How to use examples: IAuthorizationFilter AuthorizeAttribute

By implementing the
public class ClaimRequirementAttribute : TypeFilterAttribute
{
    public ClaimRequirementAttribute(string claimType, string claimValue) : base(typeof(ClaimRequirementFilter))
    {
        Arguments = new object[] { new Claim(claimType, claimValue) };
    }
}

public class ClaimRequirementFilter : IAuthorizationFilter
{
    private readonly Claim _claim;

    public ClaimRequirementFilter(Claim claim)
    {
        _claim = claim;
    }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        bool hasClaim = context.HttpContext.User.Claims.Any(c => c.Type == _claim.Type && c.Value == _claim.Value);
        if (!hasClaim)
        {
            context.Result = new ForbidResult();
        }
    }
}
Copy after login
method in your filter, you can specify the authorization logic according to the statement.

The above is the detailed content of How to Implement Custom Authorization in ASP.NET Core Using Claims?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template