Home >Backend Development >C++ >How to Create a Custom AuthorizeAttribute in ASP.NET Core for Simple Claim Requirements?

How to Create a Custom AuthorizeAttribute in ASP.NET Core for Simple Claim Requirements?

Susan Sarandon
Susan SarandonOriginal
2025-02-01 18:21:09778browse

How to Create a Custom AuthorizeAttribute in ASP.NET Core for Simple Claim Requirements?

Create a custom AuthorizeAttribute in ASP.NET CORE to meet the simple statement requirements

In the early version of ASP.NET CORE, you can create custom

by rewriting bool AuthorizeCore(HttpContextBase httpContext). However, this method no longer exists in . AuthorizeAttribute AuthorizeAttribute The current method of creating custom

is to use new strategic design, and its document

Here AuthorizeAttribute. The basic idea of ​​this new method is to use the new feature to specify a "strategy" (such as ). This strategy is registered in the [Authorize] Having an age statement, the age is 18 or more). [Authorize(Policy = "YouNeedToBe18ToDoThis")] Startup.cs Strategic design is a good supplement to the framework, and the core team of ASP.NET security should praise it for this. In other words, it is not suitable for all situations. The disadvantage of this method is that it fails to provide a convenient solution for the most common needs: simply asserting a given controller or operating statement that needs to be given. If the application may have hundreds of discrete permissions to manage CRUD operations on a single REST resource ("CancreateRorder", "Canreadordorder", "CanupDateorder", "Candeleteorder", etc.), the new method must either require the strategy name and declaration name Repeat one -to -one mapping (e.g.

), either write some code to perform these registrations during runtime (for example, read all the types of declarations from the database and execute the above calls in the cycle). For most cases, the problem of this method is that it is an excess overhead.

options.AddPolicy("CanUpdateOrder", policy => policy.RequireClaim(MyClaimTypes.Permission, "CanUpdateOrder")); Although the ASP.NET CORE security team recommends not to create your own solution, in some cases, this may be the most cautious starting option.

The following is the implementation of . It provides a simple method to express the requirements of a given controller or operation declaration:

The above is the detailed content of How to Create a Custom AuthorizeAttribute in ASP.NET Core for Simple Claim Requirements?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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