c# - MVC 在不注销的情况下授权属性工作

标签 c# asp.net-mvc asp.net-mvc-5

我有一个只有特定 Active Directory 组才能访问的 Controller 类。

[Authorize(Roles = @"Domain\GroupName")]
public class AdminToolsController : Controller
{
    ...
}

现在我正在测试..我目前不在组中..但如果我添加自己..并且我尝试访问此 Controller 中的任何内容,我仍然会被要求登录并且我的凭据不起作用。但是..如果我添加自己..然后注销..然后重新登录..然后尝试访问此 Controller 中的任何内容它会识别我并允许我访问。

有没有办法立即做到这一点?也就是说,我能否将自己添加到组中并成功访问 Controller 内的任何方法,而无需注销并重新登录?

更新

我在下面编辑了 Camilo Terevinto 的回答。他们出于某种原因的回答.. 每当我从特定组中添加或删除我自己时.. 该组不会成为变量 groups 的一部分。

这是我的更新:

public class AuthorizeByActiveDirectoryGroups : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var roles = Roles.Split(',');
        using (var domainContext = new PrincipalContext(ContextType.Domain, "domainname"))
        {
            var user = httpContext.User.Identity.Name;
            using (var domainUser = UserPrincipal.FindByIdentity(domainContext, httpContext.User.Identity.Name))
            {
                var adgroup = GroupPrincipal.FindByIdentity(domainContext, "Domain\\GroupName");
                bool member = domainUser.IsMemberOf(adgroup);
                var groups = domainUser.GetAuthorizationGroups();
                return member;
            }
        }
    }
}

最佳答案

IIRC,当您使用默认的 Windows 身份验证登录时,角色只会获得一次,因此为了始终获得最新的,您可以使用自定义属性。
由于这将始终检查 AD 值,您可以使用一些缓存并仅在需要时刷新值,但这取决于您的具体情况。

注意:我现在没有 VS,所以可能存在一些拼写问题

public class AuthorizeByActiveDirectoryGroupsAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var roles = Roles.Split(",");
        using (var domainContext = new PrincipalContext(ContextType.Domain))
        {
            using (var domainUser = UserPrincipal.FindByIdentity(domainContext, httpContext.User.Identity.Name))
            {
                var groups = domainUser.GetAuthorizationGroups();
                return groups
                    .Select(x => x.Name) // the group name
                    .Any(x => roles.Contains(x)); // any group is one of the specified in the Roles property of the attribute
            }
        }
    }
}

所以你会像这样使用它:

[AuthorizeByActiveDirectoryGroups(Roles = "Group1,Group2")]
public ActionResult Index()
{
    return View();
}

关于c# - MVC 在不注销的情况下授权属性工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45245077/

相关文章:

c# - 如何使用 XmlSerializer 序列化内部类?

c# - 未知 url 的 MVC 3 路由

c# - 如果我不实现分部方法会怎样?

c# - 使用模型作为参数将操作重定向到其他区域的操作

asp.net-mvc - MVC Razor 中的 Foreach 循环计数器

c# - ASP.Net MVC 5 Forms Authentication 在代码后面获取用户名

c# - 使用 JavaScript 从 C# 执行 doPostBack

c# - 选择参数中的默认值为 DateTime.Now

asp.net-mvc - 如何在 MVC4 表单中编辑子对象?

javascript - 带字幕的多图像文件上传