Reputation: 2259
I know this has been answered here before, however even after following all the solutions I could find, I cannot still get my roles working in my system.
I have a Asp.Net MVC application, with Forms based authentication. Instead of using a local database, it uses OpenAuth/OpenID for authentication, and a database lookup table for application roles.
As per main suggestion, I implemented the roles in Global.asax
like:
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
//Fires upon attempting to authenticate the use
if (HttpContext.Current.User != null &&
HttpContext.Current.User.Identity.IsAuthenticated &&
HttpContext.Current.User.Identity.GetType() == typeof (FormsIdentity))
Thread.CurrentPrincipal = HttpContext.Current.User = OpenAuthPrincipal.Get(HttpContext.Current.User.Identity.Name);
}
Here OpenAuthPrincipal.Get
is a very straightforward static method wrapping the openauth id with the roles:
public static IPrincipal Get(string userId)
{
var db = new WebData();
var user = db.Users.Find(userId);
return new GenericPrincipal(new Identity(user), user.Roles.Split('|'));
}
However when I reach a function like:
[Authorize(Roles = "Admin")]
public ActionResult Edit(int id)
{
...
}
It fails. If I remove the Roles restriction, and check User.IsInRole("Admin")
in the debugger I get a false
. However, if I do the check in the Global.asax
, I get true
.
I know that the User.Identity.Name is coming correctly. And also the IIdentity is not modified at all. However only the roles are lost.
What could be the cause of this issue?
Update:
The solution recommended below did not directly work, however this change fixed the issue for me:
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
{
httpContext.User = OpenAuthPrincipal.Get(httpContext.User.Identity.Name);
return base.AuthorizeCore(httpContext);
}
Upvotes: 1
Views: 753
Reputation: 1038810
As per main suggestion, I implemented the roles in Global.asax like:
No idea where did you get this main suggestion from but in ASP.NET MVC you normally use authorization action filters. And since the default Authorize filter doesn't do what you need, you write your own:
public class OpenIdAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var authorized = base.AuthorizeCore(httpContext);
if (authorized)
{
httpContext.User = OpenAuthPrincipal.Get(httpContext.User.Identity.Name);
}
return authorized;
}
}
and then:
[OpenIdAuthorize(Roles = "Admin")]
public ActionResult Edit(int id)
{
...
}
Upvotes: 2