我正在开发一个项目,将使用Windows角色提供程序,并且我想将功能限制在特定的AD组中。
在MVC中,我可以在我的操作方法上方使用AuthorizeAttribute并相应地重定向。对于不使用MVC的标准Web Forms应用程序(.NET 3.5),是否有类似的操作方法?
在MVC中,我可以在我的操作方法上方使用AuthorizeAttribute并相应地重定向。对于不使用MVC的标准Web Forms应用程序(.NET 3.5),是否有类似的操作方法?
<configuration>
<system.web>
<authorization>
<allow roles="domainname\Managers" />
<deny users="*" />
</authorization>
</system.web>
</configuration>
基本上,当使用<authentication mode="Windows" />
时,域组被翻译为角色。
您可以在MSDN上阅读更多信息
interface IMyPrincipal : IPrincipal
{
string MyId { get; }
string OrgCode { get; }
string Email { get; }
}
和校长
public class MyPrincipal : IMyPrincipal
{
IIdentity identity;
private List<string> roles;
private string email;
private string myId;
private string orgCode;
public MyPrincipal(IIdentity identity, List<string> roles, string myId, string orgCode, string email)
{
this.identity = identity;
this.roles = roles;
this.myId = myId;
this.orgCode = orgCode;
this.email = email;
}
public IIdentity Identity
{
get { return identity; }
}
public bool IsInRole(string role)
{
return roles.Contains(role);
}
public string Email
{
get { return email; }
}
public string MyId
{
get { return myId; }
}
public string OrgCode
{
get { return orgCode; }
}
}
并创建了一个用于页面上的属性
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class AdminAuthorizationAttribute : Attribute
{
public AdminAuthorizationAttribute()
{
var user = (MyPrincipal)HttpContext.Current.User;
if (user.IsInRole("MyAdmin"))
return;
throw new AccessDeniedException();
}
}
并创建了一些自定义异常
public class AccessDeniedException : BaseHttpException
{
public AccessDeniedException() : base((int)HttpStatusCode.Unauthorized, "User not authorized.") { }
}
public class BaseHttpException : HttpException
{
public BaseHttpException(int httpCode, string message) : base(httpCode, message) { }
}
[AdminAuthorization]
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
在全局范围内设置一个通用的[Authorize]属性的好方法,而不指定角色,是将以下代码放入项目的web.config文件中的<system.web>标签内。
<authorization>
<deny users="?" />
<allow users="*" />
</authorization>
这将只允许任何经过身份验证的用户访问文档,并最终触发重定向到身份验证页面。这相当于 MVC 中的通用 [Authorize]。
if(User.IsInRole("somerole"))
的检查。 - Klaus Byskov Pedersen