hello everyone,
I am working on asp.net mvc web api
In my api, i have 4 methods, I want to give access (authorize) to 2 methods to particular user and for other user it should say unauthorized
I am using JWT token to authorize methods to specific user

Aman GuptaRank #193 · 12.4K reputationPosted Jan 17, 2023, 9:36 PM EST
Hello,
Your approach to use JWT Token is correct could you please describe your issue.
Thanks
Sushant TorankarRank #3,026 · 476 reputationPosted Jan 17, 2023, 10:55 PM EST
Hello,
Thank you for reply.
My api has 4 method , but I want to give access to specific user. All users cannot access it.
Using JWT, it allows access to any user.
So I want to unauthorised api or methods to specific users
Pasang TamangRank #449 · 5.6K reputationPosted Jan 17, 2023, 11:12 PM EST
Hi,
For this you can do restriction with roles. All your users should have a role assigned. Please check below articles to see how the implementation can be done.
https://www.c-sharpcorner.com/article/jwt-token-creation-authentication-and-authorization-in-asp-net-core-6-0-with-po/
Regards,
Pasang
Vishal JoshiRank #377 · 6.7K reputationPosted Jan 17, 2023, 11:54 PM EST
Hello
To authorize authenticated users, use the [Authorize] attribute.
To authorize specific roles or users, that is when you'll have [Authorize (Users = "someuser")] or [Authorize (Roles = "somerole")].
Thanks
Sushant TorankarRank #3,026 · 476 reputationPosted Jan 17, 2023, 11:59 PM EST
Thank you all for reply.
Is there any other way other than setting up ROLES in Authorize attribute?
Vishal JoshiRank #377 · 6.7K reputationPosted Jan 18, 2023, 12:06 AM EST
Hello Sushant,
You can set it by USERS.
[Authorize (Users = "someuser")] public ActionResult AdminUsersIndex() { return View(); }Thanks
Sachin SinghRank #66 · 26.2K reputationPosted Jan 18, 2023, 12:37 AM EST
I am guessing you must be using Owin as you are using web api 2 and not core api.
so inside your GrantResourceOwnerCredential method, you can add claims of RoleType
var identity = new ClaimsIdentity("JWT"); identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); identity.AddClaim(new Claim("sub", context.UserName)); identity.AddClaim(new Claim(ClaimTypes.Role, "Manager")); identity.AddClaim(new Claim(ClaimTypes.Role, "Supervisor"));Sushant TorankarRank #3,026 · 476 reputationPosted Jan 18, 2023, 4:57 PM EST
Thank you all for your reply
Roles or User options is working.
Is there any other way to achieve it ?
thank you
Pasang TamangRank #449 · 5.6K reputationPosted Jan 18, 2023, 11:00 PM EST
Hi,
User role is the best approach to do. If you want to go with other option then still you will need some flag to check access level and you have to do some additional work for authorization. In user table you can add a column PageAccess or similar one and add all the URL that the user can access with comma separated. Then in your Web API method you have to check if user have access or not.
Regards,
Pasang