9

I have a controller which is protected by the [Authorize] attribute.

This works very good (I am sent back to login if I am not logged in), but I wish to add some roles to this attribute, I've read that its possible to do something like [Authorize(Roles = "Customer"] but when I do this I am instantly sent back to the login page on my application?

Is this Roles override not working with the new ASP.NET Identity? On my user creation I am adding the user to the by the following code:

var user = new ApplicationUser {UserName = model.Username};
var result = UserManager.Create(user, model.Password);
if (result.Succeeded)
{
    UserManager.AddToRole(user.Id, "Customer");
    SignIn(user, false);

    return RedirectToAction("Done");
}

And according to the database the user is in this role. Why is this not working? Am I missing a configuration or some sort?

kyrylomyr
  • 12,192
  • 8
  • 52
  • 79
janhartmann
  • 14,713
  • 15
  • 82
  • 138

5 Answers5

9

I am going to answer my own question.

The reason this was not working (hours of digging around) it was because my context had the following:

Configuration.ProxyCreationEnabled = false;

This made lazyloading disabled and therefore roles not included, when the user was loaded!

So the fix was to enable this or remove the line.

UPDATE: 2015-05-01

This was a bug, fixed in the 2.0.0-alpha1 release. Thus, this workaround is no longer necessary going forward, and the Roles will load regardless of this setting.

Does Identity Owin require LazyLoading?

Community
  • 1
  • 1
janhartmann
  • 14,713
  • 15
  • 82
  • 138
  • 2
    wow! hit the same issue, spent all of last night trying to figure out why claims were not loading for user roles! Great catch, thanks! – Sandeep Phadke Jan 31 '14 at 20:13
  • Nice find. Also had me scratching my head for hours. I'm not sure why it needs to rely on lazy loading to get roles for a user. Would love to see some more in-depth insights into this. Anyone? – Adrian Brown Apr 08 '14 at 13:58
  • I am unable to replicate this behavior with the latest release of ASP.Net Identity. I had a different issue, which led me to this post, however, neither Configuration.ProxyCreationEnabled = false, nor toggling Configuration.LazyLoadingEnabled makes any difference. It loads Roles in both cases. – Pittsburgh DBA May 01 '15 at 18:42
  • It turns out that this was a bug, which was subsequently fixed. Thus, we no longer need such a workaround. http://stackoverflow.com/questions/20868836/does-identity-owin-require-lazyloading – Pittsburgh DBA May 01 '15 at 18:49
  • I will update the question/answer when im on a computer again. Thanks for this – janhartmann May 01 '15 at 18:50
  • 1
    @janhartmann many thanks for your post! It was a great part of my path of discovery. – Pittsburgh DBA May 01 '15 at 19:27
0

Create a role like so:

RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new MyDbContext()));
var roleresult = RoleManager.Create(new IdentityRole(roleName));

Then, add a user like so:

var currentUser = UserManager.FindByName(user.UserName); 
var roleresult = UserManager.AddToRole(currentUser.Id, "Superusers");

Please let me know if this works for you.

user1477388
  • 20,790
  • 32
  • 144
  • 264
  • This is already the way I create roles and adding users to roles, the problem is that the the check for the role is false. – janhartmann Jan 08 '14 at 17:59
0

It works fine with AspNet Identity in my case. Are you sure you:

  • haven't customized Authorization filters or done it right?
  • haven't reconfigured authentication/authorization in web.config?
  • have proper entries in AspNet Identity tables: AspNetUsers, AspNetRoles, AspNetUserRoles (the role exists and the user has it)?
Marcin Wachulski
  • 567
  • 4
  • 14
  • How should the authorization look like in web.config? I am using no other filters than errorhandling. – janhartmann Jan 08 '14 at 20:16
  • Are there any elements named authentication or authorization in your web.config, what are they values? – Marcin Wachulski Jan 08 '14 at 20:22
  • No there is not. I have even tried putting the default: in together with - without any luck either. – janhartmann Jan 08 '14 at 20:35
  • Last check: table data entries (Server Explorer -> Data Connections -> DefaultConnection [might be other] -> there are AspNet Identity tables). If there is a correct match - no idea without looking at code. – Marcin Wachulski Jan 08 '14 at 20:41
  • Yes they are there. Also filled with correct data and correct relationship. I am beginning to think maybe when the user is loaded its roles is not populated. Lazy loading. But i havent configurered my app not to use LL – janhartmann Jan 08 '14 at 20:55
0

Checkout this answer: ASP.NET Identity check user roles is not working

In your case, while checking for the case, compare the case of IdentityRole record and Authorize Attribute. Do not compare with the UserManager.AddToRole(user.Id, "Customer");

Community
  • 1
  • 1
jd4u
  • 5,789
  • 2
  • 28
  • 28
0

i write a sample to test it,it works good.so i think there 2 points
1.you cookie not save to browser
2.you cookie not with a role info

check you cookie, is there a cookie named ".AspNet.ApplicationCookie" (default name)
if not so check you broswer allow write cookie,or the code you write cookie
if exsit ,you can create a class extends

ISecureDataFormat<AuthenticationTicket>  

and config

app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            TicketDataFormat=new T()

        });

new T() is the class
in this class you need do

public string Protect(AuthenticationTicket data)

and

public AuthenticationTicket Unprotect(string protectedText)

it is some thing about serialize
you can set a break point,and check the data,
in data.Identity.Claims (a IEnumerable< Claim>) should have a Claim with your role info

chenZ
  • 920
  • 4
  • 16