从web.Config授予Controller级别的用户权限

时间:2013-09-26 21:50:13

标签: asp.net-mvc

在我的控制器中[Authorized]注释。

我想获取在我的web.config文件中设置的授权用户列表。

<add key="authorizedUsers" value="jeff,dan,mindy,claudia"/>

我知道在控制器中你可以做类似的事情:

[Authorize Users="jeff,dan,mindy,claudia"]

但我宁愿只更新web.config文件而不必重新编译。无论如何都要读取我的列表的web.config文件,然后将其添加到[Authorize]属性?我也使用Windows身份验证而不是表单身份验证。

2 个答案:

答案 0 :(得分:7)

您可以实现继承自AuthorizeAttribute的自定义AuthorizeAttribute。

我假设您正在使用FormAuthentication。否则,它将无效。

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class CustomUserAuthorizeAttribute : AuthorizeAttribute
{
    private string[] _usersSplit
    {
        get
        {
            var authorizedUsers = ConfigurationManager.AppSettings["authorizedUsers"];

            return authorizedUsers.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries);
        }
    }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext == null)
            throw new ArgumentNullException("httpContext");
        IPrincipal user = httpContext.User;
        return user.Identity.IsAuthenticated && (_usersSplit.Length <= 0 || Enumerable.Contains(_usersSplit, user.Identity.Name, StringComparer.OrdinalIgnoreCase));
    }
}

用法

[CustomUserAuthorize]
public ActionResult Test()
{
    ViewBag.Message = "Your page.";

    return View();
}

仅供参考:理想情况下,您希望使用基于角色的身份验证,并将其存储在数据库中。它有点容易维护。但是,这取决于您的需要。

答案 1 :(得分:0)

你不是那样做的。您需要将这些用户设置为角色,然后在web.config文件中授予角色访问权限。

<system.web>
  <authorization>
    <allow roles="admin"/>
  </authorization>
</system.web>

你可以这样做;

<authorization>
    <allow users="?"/>
    <deny users="*"/>
</authorization>

但这打开了网站潜在的黑客入侵IMO

相关问题