5

I have implemented a token based authentication web Api 2 application using OWIN middleware, authentication is made successfully where I can retrieve token and use it to get to the method of the web Api.

However when I tried to add roles authorization, it doesn't work, I've searched thoroughly and found that I have to add in the "GrantResourceOwnerCredentials " in the oAuthorization provider the following:

identity.AddClaim(new Claim(ClaimTypes.Role, "the role that i need to add"));

The above line is all that I can get, it is also found in Authorization roles WebAPI oauth owin

However still whenever I use a token to get to any method(even authorized ones with different role) it still retrieve results normally.

I mean when for example in the API Controller: it is like the following:

 [Authorize(Roles = "Admin")]
    // GET api/Patient
    public IQueryable<Patient> GetPatients()

while in the "GrantResourceOwnerCredentials" method i have added only an Employee role:

var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, "Employee"));

Also, the Table in the server explorer that holds the roles "AspNetUserRoles" is not updated.

What I'm missing???

Community
  • 1
  • 1
user1874288
  • 135
  • 2
  • 11
  • Well you are creating claims not roles so the table wouldn't update. Have you tried creating the role manually in the database and adding a reference to a user there? – grimurd Feb 09 '15 at 23:20
  • @ GirmurD:I have added two roles manually in the database: in Table "ASPNetRules" and updated also assign roles to users using "AspNetUserRoles" Table, but still the same, any token can access the Authorized method stated above. – user1874288 Feb 09 '15 at 23:24
  • Is the user definitiely connected to that role? There should be a AspNetUser, AspNetRoles and AspNetUserRoles table yes? The roles are in the AspNetRoles table and you put a user into a role in the AspNetUserRoles table? Did you do that? Did it make a difference? – grimurd Feb 09 '15 at 23:28
  • yes. the register method in the account controller fill AspNetUser Table then i updated the AspNetRoles, and AspNetUserRoles manually. as far as i know that when using token authentication, i have to add the role in the form of a claim oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, "Employee")); //after i have defined the employee role in the tables mentioned earlier. still any token can get to the method !!! – user1874288 Feb 09 '15 at 23:34
  • Have you tried the answers here: http://stackoverflow.com/questions/20132795/asp-net-identity-check-user-roles-is-not-working – grimurd Feb 09 '15 at 23:37
  • Look at this: https://www.linkedin.com/pulse/securing-net-core-web-api-identityserver4-resource-owner-dalvandi?trk=mp-author-card – Behrooz Dec 07 '16 at 18:39

0 Answers0