简体   繁体   中英

how to implement custom authorization asp.net core mvc

So, here's my situation: I have a .net framework blackbox that I ask for user's roles (i give it username and it returns collection of permissions).

In my old .net framework asp.net mvc application, I use windows authentication and then override two events in global.asax.cs and use my own principal containing the permissions (and an implementation of authorizeAttribute taking enum values in contructor).

  1. I first check if user is authneticated and if there is a cookie with his permissions (encrypted). If there is not (or expired), I create new principal and load permissions from my databse, which is then ecrypted and saved into a cookie.

  2. The second event then takes the cookie (if it's there) and takes my custom principal from it, which contains the permissions, and uses it as current principal.

  3. The authorize attribute then just looks into current httpcontext if there are permissions and I don't have to call database every time to get user's permissions, as it is costly in time (the network is slow).

Now I'm facing a challenge of how to implement this in asp.net core 3. All I have read so far talks about how to replicate the "call for permissions every time you need to check something" approach which is precisely what I do not want to do.

Is there another approach that would let me do something similar to the .net framework asp.net way (load the data once every n minutes as the cookie expires and the user is browsing and save them somewhere and then use them), but in ASP.NET CORE?

You can implement claims-based authorization via policies . After setting windows authentication in your application, in IClaimsTransformation, you can query the roles/permissions based on user id in database, and roles/permissions claim to ClaimsPrincipal. After that you can use Authorize attribute to check specific policy(based on claims) after authentication.

You can click here for code sample.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM