我想实现自定义AuthorizeAttribute
。
我有自定义用户:
public class MyUser : IPrincipal
{
public List<string> Roles { get; set; }
public IIdentity Identity{ get; set; }
public bool IsInRole(string role){ return Roles.Contains(role); }
}
在global.asax
protected void Session_Start(object sender, EventArgs e)
{
MyUser user = new MyUser();
user.Identity = User.Identity;
user.Roles = new List<string>();
user.Roles.Add("MyRole");//I will get them from AD
HttpContext.Current.User = user;
}
和属性
public class AuthorizeADAttribute : AuthorizeAttribute
{
public string Roles { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
MyUser user = (MyUser)httpContext.User;//User is not MyUser
if (user.Roles.Contains(Roles))
{
return true;
}
return false;
}
protected override void HandleUnauthorizedRequest(
AuthorizationContext filterContext)
{
...
}
}
问题是httpContext.User
会返回System.Security.Claims.ClaimsPrincipal
。
为什么会发生这种情况?如何从session_start
访问我的用户?
答案 0 :(得分:1)
您需要在Application_PostAuthenticateRequest
的{{1}}事件处理程序中覆盖其值。