Json Web Token - How to create a token that accesses only a particular Controller or Action?

Asked

Viewed 228 times

0

I am implementing JWT in a. Net Core 2.0 application and would like to know how to restrict token access to certain controllers.

2 answers

2

What you want to do can be done with Roles and Claims.

For example, during Voce authentication you can add a Role in "Shopping" or "Sales" token".

In token: "roles": ["Compras", "Vendas"] //Add roles that the user has access to.

In controller shopping:

[Authorize(Roles = "Compras")]
public class ComprasController : Controller

In the controller sales:

[Authorize(Roles = "Vendas")]
public class VendasController : Controller

Thus, the two controllers needed to be authenticated, but will only be accessed if the authenticated user has the Role specifies.

Follow a reference to this implementation: https://www.jerriepelser.com/blog/using-roles-with-the-jwt-middleware/

I hope I’ve helped!

0

To restrict a Controller with a JWT, that is, oblige access to it with only one Token, place the attribute Authorize on top of the Controller desired:

[Authorize]
[Route("[controller]")]
public class AuthController : Controller
{ }

Thus, all the methods of this Controller will need a Token to be accessed.

If you want to define a method that does not require a Token, place the attribute AllowAnonymous on top of the desired method:

[AllowAnonymous]
[HttpPost("Token")]
public IActionResult CreateToken([FromBody]Login login)
{ }

For a full and functional tutorial on how to create an ASP.NET Core application with JWT, you can follow this tutorial: Securing ASP.NET Core 2.0 Applications with Jwts

  • Actually what I wanted was more or less like this, I have two controllers, I want a generated token to have access to one but not the other. Both of which would require a token to be accessed. I mean to which specific controllers that token can access.

  • That is, exactly what I wrote above. You want a Controller to need Token, put Authorize. You don’t want the Controller to need Token, don’t put.

  • No. I want everyone to need Authorize. But the token only has access to specific Authorizes. Let’s say I have an API to meet the sales and shopping area. Both areas need to have their methods protected, but the sales area token cannot access the purchases and vice versa.

  • For this, you can make use of Claims, which are nothing more than some data that you can pass along with the Token to do the validation later when arriving in your API. In this case, you would use the same token, but passing the desired area along with the token. When the request arrives in the API, you check whether such an area can access the resource or not. The link I put in the reply also explains how to make use of Claims.

  • Blz, thanks for your help

Browser other questions tagged

You are not signed in. Login or sign up in order to post.