AuthorizeAttribute with ASP.NET Identity
Asked Answered
R

5

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?

Recife answered 8/1, 2014 at 17:9 Comment(5)
Are you sure that user is in the Customer role?Cloutman
Yes, the customer is coming from a constant I useRecife
I mean, when you go to Project -> ASP.NET Configuration, go to security tab then click Create/Manage Roles. Check for your Role. Then go to users and check for your user. Be sure to check out part 7 of the Music Demo for Microsoft asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-7Cloutman
That is for the old Membership - I am using ASP.NET Identity?Recife
Sorry, you are correct. Please see my answer (which I am about the write).Cloutman
R
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?

Recife answered 10/1, 2014 at 16:35 Comment(6)
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!Setter
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?Germainegerman
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.Thebaine
It turns out that this was a bug, which was subsequently fixed. Thus, we no longer need such a workaround. #20869336Thebaine
I will update the question/answer when im on a computer again. Thanks for thisRecife
@Recife many thanks for your post! It was a great part of my path of discovery.Thebaine
C
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.

Cloutman answered 8/1, 2014 at 17:48 Comment(1)
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.Recife
D
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)?
Durwin answered 8/1, 2014 at 20:14 Comment(5)
How should the authorization look like in web.config? I am using no other filters than errorhandling.Recife
Are there any elements named authentication or authorization in your web.config, what are they values?Durwin
No there is not. I have even tried putting the default: <modules><remove name="FormsAuthenticationModule" /></modules> in together with <authentication mode="None" /> - without any luck either.Recife
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.Durwin
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 LLRecife
E
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");

Extine answered 9/1, 2014 at 6:11 Comment(0)
C
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

Christianechristiania answered 9/1, 2014 at 9:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.