如何将自定义参数传递给授权策略 [英] How to pass custom argument to authorization policy

查看:95
本文介绍了如何将自定义参数传递给授权策略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在asp.net核心MVC中为我的其余API提供一个自定义属性.我想将此属性可选地添加到一些API中.此属性根据某些条件检查用户是否可以访问该API,如果无法访问,则抛出403.我当时使用过滤器来实现此目的,而过滤器的问题是无论属性是否添加到我的API中,都会执行过滤器代码. 我希望仅当将此属性添加到API时才执行过滤器代码.
我的同事建议我针对此用例使用授权策略,而不要使用过滤器.仅当将策略添加到API时,才会执行策略.另外,由于我抛出403,因此授权策略是更好的选择.我研究了授权策略,但是我的问题是我无法将自定义属性传递给授权策略.

I need a custom attribute for my rest API in asp.net core MVC. I want to add this attribute optionally to some of my APIs. This attribute checks if the API is accessible to user or not based on some condition and throws a 403 if it's not accessible. I was using filters to achieve this and the issue with filter is that filter code gets executed whether the attribute is added or not to my API. I would want that my filter code is executed only when this attribute is added to the API.
My colleague suggested that I should be using authorization policy instead of filters for this use case. Policies are executed only when it's added to the API. Also since I am throwing 403, authorization policy is a better candidate. I explored authorization policy but my issue is I am unable to pass custom attributes to Authorization policy.

例如,我能够使用过滤器和自定义属性来做到这一点.

For example, I was able to do this using filters and custom attributes.

[MyCustomFeature("param1", "param2")]

如何在授权策略中执行相同的操作?我将此示例用于授权策略. 自定义授权属性asp.net核心

How can I do the same in authorization policy? I am using this example for authorization policy. Custom Authorization attribute asp.net core

推荐答案

请参见

See here. Strongly recommend reading top to bottom.

总结是,无论您如何接入基于策略的身份验证系统,策略始终都是通过单个字符串来解析的.因此,要获得想要的东西,您需要:

The summary is that, regardless of how you tap in to the policy-basd auth system, a policy is always resolved via a single string. So, to get what you want, you need to:

  • 实现一个自定义属性,该属性将AuthorizeAttribute子类化,并接受您传入的参数,并使用它们生成策略名称字符串.仔细阅读链接的文档页面中的自定义授权属性"示例,查看其如何在策略字符串中实际存储年龄"的值.
  • 实施并注册一个自定义IAuthorizationPolicyProvider,该IAuthorizationPolicyProvider可以解释由您的自定义属性生成的字符串,并即时生成适当的策略.
  • Implement a custom attribute that subclasses AuthorizeAttribute and that takes the arguments you pass in and uses them to generate a policy name string. Read the "Custom Authorization attributes" example in the linked docs page closely, see how it actually stores the value of "Age" in the Policy string.
  • Implement and register a custom IAuthorizationPolicyProvider that can interpret the strings generated by your custom attribute and generate the appropriate policy on the fly.

涉及的代码并不多,而且也不是很复杂,但是归结为将内容放入字符串中有点奇怪/尴尬.

There's not a ton of code involved and it's not super complex, but it's a little strange/awkward that it comes down to putting stuff into a string.

这篇关于如何将自定义参数传递给授权策略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆