views:

54

answers:

2

Using this code for authentification:

HttpContext.Current.User=new GenericPrincipal
  (new GenericIdentity(user.UserName), roles);
FormsAuthentication.SetAuthCookie(user.UserName,false);

Problem is - on next request, HttpContext.Current.User.IsAuthenticated is true, but HttpContext.Current.User.IsInRole("admin") is false.

There are a lot of info on google but somehow nothing helps as usual.

Tried to add this to my web.config:

<system.web>
  <roleManager enabled="false" />
</system.web>

I do not want to use membership provider.

Any tips?

+1  A: 

I think you might be trying to use the wrong kind of Identity if you're using forms authentication. You might be better off using FormsIdentity.

Article on Best Practices for Forms Authentication (might be outdated)

Joseph
`genericIdentity` haven't property `Roles`
Arnis L.
IsInRole is on IPrincipal
Russ Cam
@Joseph my mistake. actually - I do call it on user.
Arnis L.
@Amit ok I thought it probably was but I might have found something else anyway
Joseph
@Joseph that looks promising. Overcomplicated as usual, but might actually work.
Arnis L.
Does not help either. It does decrypt identity from cookie, set it to `HttpContext.Current.User` but inside controller action, `User.IsInRole("admin")` still is false. The same scenario as before.
Arnis L.
@Amis What's in your HttpContext.Current.User's Roles property?
Joseph
There is no `Roles` property on `HttpContext.Current.User`.
Arnis L.
This helped - http://stackoverflow.com/questions/1385042/asp-net-mvc-forms-authentication-authorize-attribute-simple-roles/2342196#2342196 Had to switch roleManager back to false in web.config and it finally works. God that was intuitive...
Arnis L.
I hate it when something that seems like it should be so easy ends up being so difficult.
Joseph
A: 

Look like the IsInRole method is on the wrong interface. Try

HttpContext.Current.User.IsInRole("admin")
samy
Nah, that was just a typo. Didn't double check and wrote example as I remembered it. It's not solution. HttpContext.Current.User.Identity.IsInRole doesn't even compile.
Arnis L.