【问题标题】:windows authentication to get a list of users in MVC4Windows身份验证以获取MVC4中的用户列表
【发布时间】:2014-02-28 11:08:20
【问题描述】:

我的应用程序使用 Windows 授权,但我手动指定有权访问的用户,如下所示:

[Authorize(Users = "domain\\userone, domain\\usertwo, domain\\userthree")]

我想知道是否可以在其中放置一个循环来遍历从数据库调用返回的用户列表,例如,一个可以从数据库中获取用户 NT 帐户列表的快速模型:

List<string> users = new List<String>();

SqlConnection con = new SqlConnection(Properties.Default.ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = @"SELECT NT_ACCOUNT FROM USERS";

SQLDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
    users.Add(reader.GetValue(reader.FieldCount));
}

以及我认为授权的样子:

foreach(String nt_account in users)
{
[Authorize(Users = nt_account)]
}

或者我不确定使用 linq 查询可能会更容易,不过上面的代码只是一个猜测。

【问题讨论】:

  • 如果要允许所有用户,为什么不只使用 [Authorize]?
  • @Sunny 因为用户列表已经是一个表,但不是该列表中的每个人都应该被允许访问,如果在门户中拥有一些允许或禁止访问的功能会很好。
  • 好的,那你需要修改AuthorizeCore方法,看这个链接:stackoverflow.com/a/6426328/1057667

标签: c# asp.net-mvc asp.net-mvc-4 windows-authentication


【解决方案1】:

修改 AuhorizeCore 方法:

protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext == null)
        {
            throw new ArgumentNullException("httpContext");
        }

        IPrincipal user = httpContext.User;
        if (!user.Identity.IsAuthenticated)
        {
            return false;
        }

        //_usersSplit = ListOfAuthorizedNames
        if ((_usersSplit.Length > 0 && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase)) && (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole)))
        {
            return false;
        }

        return true;
    }

取自:https://stackoverflow.com/a/6426328/1057667

【讨论】:

  • 试一试,应该是解决方案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-20
  • 1970-01-01
  • 2013-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-19
相关资源
最近更新 更多