我有一个使用Windows身份验证的mvc内部网应用程序。它目前有一个控制器有三个动作。
第一个动作(索引)应该对每个人都可用,这没问题。第二个和第三个操作应仅对特定DOMAIN中的用户可用。但是<Authorize()>
标记只给出了两个选项:角色或用户。我尝试使用用户并将其设置为'DOMAIN *'和'DOMAIN \?'但这不起作用。
我一直在网上搜索,但似乎找不到任何方法来完成我想要的东西。我希望有人可以帮助我!
答案 0 :(得分:10)
使用DOMAIN\Domain Users
作为角色名称。它是一个内置的组,包含,你猜对了,域中的所有用户。
答案 1 :(得分:5)
添加到jrummel提到的内容,使用以下内容装饰您的控制器或操作:
[Authorize(Roles = "DOMAIN\Domain Users")]
这将只允许特定角色的用户(在此特定域的用户中)访问控制器/操作(取决于您装饰的用户)。或者,您可以为域的目的创建自己的授权属性:
/// <summary>
/// Specified which domains a user should belong to in order to access the decorated
/// controller/action
/// </summary>
public class DomainAuthorizeAttribute : AuthorizeAttribute
{
private String[] domains = new String[0];
/// <summary>
/// List of acceptable domains
/// </summary>
public String[] Domains
{
get { return this.domains; }
set { this.domains = value; }
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
// User not logged in
if (!httpContext.User.Identity.IsAuthenticated)
{
return false;
}
// No roles to check against
if (this.Domains.Length == 0)
{
return true;
}
// check if they're on any of the domains specified
String[] roles = this.Domains.Select(d => String.Format(@"{0}\Domain Users", d)).ToArray();
if (roles.Any(httpContext.User.IsInRole))
{
return true;
}
return false;
}
}
这样的事情应该允许你这样做:
[DomainAuthorize(Domains = new[]{ "DOMAIN1", "DOMAIN2" })]
答案 2 :(得分:2)
对于感兴趣的人,这是上面代码片段的VB版本:
''' <summary>
''' Specified which domains a user should belong to in order to access the decorated
''' controller/action
''' </summary>
Public Class DomainAuthorizeAttribute
Inherits AuthorizeAttribute
Private m_domains As [String]() = New [String](-1) {}
''' <summary>
''' List of acceptable domains
''' </summary>
Public Property Domains() As [String]()
Get
Return Me.m_domains
End Get
Set(value As [String]())
Me.m_domains = value
End Set
End Property
Protected Overrides Function AuthorizeCore(httpContext As HttpContextBase) As Boolean
If httpContext Is Nothing Then
Throw New ArgumentNullException("httpContext")
End If
' User not logged in
If Not httpContext.User.Identity.IsAuthenticated Then
Return False
End If
' No roles to check against
If Me.Domains.Length = 0 Then
Return True
End If
' check if they're on any of the domains specified
Dim roles As [String]() = Me.Domains.[Select](Function(d) [String].Format("{0}\Domain Users", d)).ToArray()
For Each r In roles
If httpContext.User.IsInRole(r) Then
Return True
End If
Next
Return False
End Function
End Class
希望这会对某人有所帮助! (所有功劳归功于Brad Christie)