【问题标题】:Custom Authorization - Web Api自定义授权 - Web API
【发布时间】:2017-08-22 08:25:19
【问题描述】:

我有一个 web api,我需要为其实现自定义身份验证和授权。授权应由 Resource 和 Action 定义,如下所示:

[Authorize("users","view")]
public async Task<IHttpActionResult> GetAsync()
{
}

有什么方法可以使用自定义授权过滤器并实现它?

此外,web api 受客户端证书保护,调用者是在请求标头中传递的密钥标识符。使用自定义身份验证过滤器对密钥进行身份验证。

问候,

约翰

【问题讨论】:

    标签: asp.net-web-api asp.net-web-api2 asp.net-identity


    【解决方案1】:

    是的,您可以创建自定义授权并放置需要授权的控制器或方法。

    示例如下

    public class CustomAuthorize : System.Web.Http.AuthorizeAttribute
        {
            private string Resource { get; set; }
            private string Action { get; set; }
            public CustomAuthorize(string resource, string action)
            {
                Resource = resource;
                Action = action;
            }
            public override void OnAuthorization(
                   System.Web.Http.Controllers.HttpActionContext actionContext)
            {
                base.OnAuthorization(actionContext);
                //Check your post authorization logic using Resource and Action
                //Your logic here to return authorize or unauthorized response 
            }
        }
    

    在这里您可以执行您的自定义授权逻辑,示例控制器将如下所示

    public class DoThisController : ApiController
    {
        [CustomAuthorize("users","view")]// for specific methods
        public string Get()
        {
            return "Sample Authorized";
        }
    }
    

    【讨论】:

    • 我想你不明白我真正的问题是什么。我想编写可以接受两个参数的自定义授权属性 - 资源和操作。我应该能够通过提供用户尝试访问的资源以及用户对资源执行的操作来定义方法的授权。
    • @SillyJohn 请根据您的特定目的检查编辑后的答案。
    • @SillyJohn 请检查您的要求,因为当您投反对票时,请给出解决方案对您无用的适当理由。我已更改为您的具体目的,这有帮助吗?
    • 为什么会出现错误找不到类型或命名空间名称“CustomAuthorizeAttribute”(您是否缺少 using 指令或程序集引用?) ....TestController.cs
    猜你喜欢
    • 2020-04-11
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 1970-01-01
    相关资源
    最近更新 更多