2

I am trying to lock down our "admin" page to only admins using Asp.net Identity (we are building in MVC5). I can get [Authorize(Users="admin")] to work but can not get [Authorize(Roles="Admin")] to work.

I have created the role in the dbo.AspNetRoles table and then associated the account in the AspNetUserRoles by pairing the user GUID to the ID in the aspnetroles table.

I have seen in previous editions of MVC you have had to get into web.config to add some lines. Can anyone help point me in the right direction?

tereško
  • 58,060
  • 25
  • 98
  • 150
Ian Anderson
  • 35
  • 1
  • 6

1 Answers1

1

Have you specified in the web.config that you are going to use roles?

  <roleManager enabled="true" defaultProvider="AspNetSqlRoleProvider">
      <providers>
        <clear />
        <add name="AspNetSqlRoleProvider" connectionStringName="DefaultConnection" applicationName="/" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
      </providers>
    </roleManager>
Josh
  • 10,352
  • 12
  • 58
  • 109
  • you need to add this right, it isn't currently there for you to modify, correct? – Refracted Paladin Nov 05 '13 at 17:54
  • @RefractedPaladin Sometimes it is, sometimes it isn't depending on what project type created the file. – Josh Nov 05 '13 at 19:34
  • 4
    This answer will not help if you are using [ASP.NET Identity](http://www.asp.net/identity), which is what MVC 5 uses out of the box. – Jeremy Cook Dec 06 '13 at 16:02
  • Using ASP.NET Identity and MVC 5, the roles are stored in the cookie by default. You may need to log off and log in again to update the roles for the user. – sean woodward Jan 15 '14 at 15:51
  • @seanwoodward: What if I've to give an admin interface to assign and de-assign roles to users, specifically using ASP.NET Identity in MVC 5? –  Feb 05 '14 at 13:37
  • @ImranNazir, even then, the user will have to log off and log in to update the roles in the cookie. The alternative is to manually check the roles or recreate the auth cookie. – sean woodward Feb 05 '14 at 18:08
  • @JeremyCook If you are using owin / identity how are you meant to do roles then? I have been struggling. – Zapnologica Feb 10 '14 at 09:37
  • @Zapnologica I've also struggled with this and here's my interpretation. Out of the box, Identity uses claims that get stored in a user's cookie at the time they sign in. Those claims can contain anything. Identity stashes the user roles I belonged to at the time I signed in into my claims. Each time I request a page Identity will look for my claims and might find one *claiming* I belong to the Admin role and then wires up that application request so that the app can see that I belong to the Admin role. Identity gets roles from my claims cookie instead from the DB by querying my username. – Jeremy Cook Feb 11 '14 at 18:52