Reputation: 22506
I want to implement custom AuthorizeAttribute
.
I have custom user:
public class MyUser : IPrincipal
{
public List<string> Roles { get; set; }
public IIdentity Identity{ get; set; }
public bool IsInRole(string role){ return Roles.Contains(role); }
}
In 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;
}
and the Attribute
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)
{
...
}
}
The problem is that httpContext.User
returns System.Security.Claims.ClaimsPrincipal
.
Why that happens and how can I access my user from session_start
?
Upvotes: 2
Views: 11213
Reputation: 47660
You need to overwrite its value in Application_PostAuthenticateRequest
event handler in your Global.asax.cs
.
See this answer for example: https://stackoverflow.com/a/10524305/54937
Upvotes: 1