Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AuthorizeAttribute with ASP.NET Identity

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?

like image 638
janhartmann Avatar asked Jan 08 '14 17:01

janhartmann


1 Answers

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?

like image 181
janhartmann Avatar answered Oct 06 '22 09:10

janhartmann