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

0

I'm implementing JWT in a .Net Core 2.0 application and would like to know how to restrict tokens access to certain Controllers.

    
asked by anonymous 27.08.2018 / 15:31

2 answers

2

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

For example, during authentication you can add a Role to the "Purchases" or "Sales" token.

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

In%% of purchases:

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

In%% of sales:

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

In this way, both controllers need to be authenticated, but will only be accessed if the authenticated user has controller specified.

Here's a reference to this implementation: link

I hope I have helped!

    
27.08.2018 / 16:18
0

To restrict a Controller to a JWT, that is, to force access to it only with a Token , set the Authorize attribute to the desired Controller :

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

In this way, all methods of this Controller will need a Token to be accessed.

If you want to define some method that does not need a Token , put the AllowAnonymous attribute over the method you want:

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

For a complete, functional tutorial on creating an ASP.NET Core application with JWT, you can follow this tutorial: Securing ASP.NET Core 2.0 Applications with JWTs

    
27.08.2018 / 15:37