2

I am working in ASP.NET MVC 5 and I am using ASP.NET Identity. I have followed LukeP's solution here to get access to my ApplicationUser custom properties (e.g. User.DisplayUsername or User.DOB). Like Luke has suggested, I now have a custom IPrincipal implementation (basically exact same code as him).

This has a problem however, and I suspect it is do with with this line of code on the CustomPrincipal class:

public bool IsInRole(string role) { return false; }

I have a controller called ReviewController and on there I have this:

[Authorize(Roles = "Admin")]
public class ReviewController : Controller
{
    // controller stuff
}

This isn't working. Even though the user I am logged in as is of role Admin. So I tried improving the code by doing this to the IsInRole method:

public class CustomPrincipal : ICustomPrincipal
{
    public IIdentity Identity { get; private set; }

    public bool IsInRole(string role)
    {
        var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new BBContext()));
        return roleManager.Roles.All(r => r.Name == role);
    }

    public CustomPrincipal(string email)
    {
        this.Identity = new GenericIdentity(email);
    }

    public string Id { get; set; }
    public string DisplayUsername { get; set; }
    public DateTime DOB { get; set; }
}

This has improved in the sense that I am now served the ReviewController. However it is still wrong because even user that are not in the Admin role are also allowed access. I know why that is too, but just don't know how to fix this.

How can I get it to work as it should?

Community
  • 1
  • 1
J86
  • 14,345
  • 47
  • 130
  • 228
  • This is way easier now using claims. Luke's answer was written around the time of MVC 3/4. MVC5 has claims support which allows you to do this without the boilerplate. – jamesSampica Apr 04 '15 at 17:00
  • I'd love it if you could point me to some code that I can follow to get my MVC5 app working with Claims :( – J86 Apr 04 '15 at 19:30
  • Identity now has built in roles support using claims also you can add custom claims for each user at log-in time. You need to update you question to describe what you want to do. – Shoaib Shakeel Apr 05 '15 at 15:24
  • You can look at this article describing new approach for adding custom properties for user and customizing identity. http://www.codeproject.com/Articles/790720/ASP-NET-Identity-Customizing-Users-and-Roles – Shoaib Shakeel Apr 05 '15 at 15:50
  • Here's how to define an extension method to get a claim from the claimsIdentity. http://stackoverflow.com/questions/27683169/identity-2-0-creating-custom-claimsidentity-eg-user-identity-getuserbyidint/27694574#27694574 – jamesSampica Apr 06 '15 at 00:37

0 Answers0