【问题标题】:Im am trying to create custom authorize attribute on my web api mvc 4 application in visual basic我正在尝试在 Visual Basic 中的 Web api mvc 4 应用程序上创建自定义授权属性
【发布时间】:2013-01-31 13:24:45
【问题描述】:

我正在尝试实现继承 system.web.http.authorizeAttribute 的自定义授权属性 在我的项目中,我有一个 web api mvc 4 模板和一个 mvc4 互联网应用程序模板 使用 Windows 身份验证作为客户端。我在 web api 控制器中有一些方法,我试图让发送请求的经过身份验证的用户无法访问这些方法 作为交换,如果他点击具有自定义属性的按钮,则应返回 401。而且如果他没有经过身份验证,客户不应该看到无权查看的东西

请帮忙提供一些代码示例!!!

【问题讨论】:

  • 请向我们展示您的尝试并告诉我们您遇到的问题。你的解决方案在做什么,你想让它做什么?

标签: .net vb.net asp.net-mvc-4 asp.net-web-api custom-attributes


【解决方案1】:

要创建从 System.Web.Http.AuthorizeAttribute 派生的自定义 AuthorizeAttribute,您应该重写 IsAuthorized() 方法。很简单,如下图。

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        // Do some condition check here

        // Return the result of the condition check
        return isAuthenticated;
    }
}

现在将[MyAuthorizeAttribute] 属性添加到您要保护的方法中。这将导致对这些方法的所有未经身份验证的请求返回 401。

更好的方法是在Controller中添加[MyAuthorizeAttribute],在不需要认证的方法中添加[AllowAnonymous]属性。

【讨论】:

  • @LeandroTupone 根据需求,使用自定义角色有不同的方式。您可以为每个角色创建自定义授权属性,或使授权属性以字符串列表(授权角色)作为参数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-29
  • 2020-04-11
  • 2014-01-23
  • 1970-01-01
  • 2015-03-03
  • 1970-01-01
相关资源
最近更新 更多