简体   繁体   English

如何实现自定义授权 asp.net core mvc

[英]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).所以,这是我的情况:我有一个 .net 框架黑盒,我要求提供用户角色(我给它用户名,它返回权限集合)。

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).在我的旧 .net 框架 asp.net mvc 应用程序中,我使用 windows 身份验证,然后在 global.asax.cs 中覆盖两个事件并使用我自己的包含权限的 enprincipal 实现。

  1. I first check if user is authneticated and if there is a cookie with his permissions (encrypted).我首先检查用户是否已通过身份验证,以及是否有具有他权限的 cookie(加密)。 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.如果没有(或过期),我创建新的主体并从我的数据库加载权限,然后将其加密并保存到 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.然后第二个事件获取 cookie(如果存在)并从中获取我的自定义主体,其中包含权限,并将其用作当前主体。

  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).然后,如果有权限,则 authorize 属性只会查看当前的 httpcontext,并且我不必每次都调用数据库来获取用户的权限,因为它的时间成本很高(网络很慢)。

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.现在我面临着如何在 asp.net 核心 3 中实现这一点的挑战。到目前为止,我所读到的所有内容都是关于如何复制“每次需要检查时都调用权限”的方法,这正是我不想要的去做。

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?是否有另一种方法可以让我做类似于 .net 框架 asp.net 的方式(每 n 分钟加载一次数据,因为 cookie 过期并且用户正在浏览并将它们保存在某处然后使用它们),但是在 Z9E0DD30438E1E38B 中?

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.在您的应用程序中设置 windows 身份验证后,在 IClaimsTransformation 中,您可以根据数据库中的用户 ID 查询角色/权限,并将角色/权限声明到 ClaimsPrincipal。 After that you can use Authorize attribute to check specific policy(based on claims) after authentication.之后,您可以在身份验证后使用Authorize属性检查特定策略(基于声明)。

You can click here for code sample.您可以单击此处获取代码示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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