I am writing a cooperative web API with asp.net core 2.1 using postgresql as db. after the user sign in user is given a JWT token that will be use for the front end side authentication (Front end will be implemented with angular 2+). I want to store the user role in JWT and when the user sign In, user role will be read from the db and it will be store (authorize Role) So I will write Roles on the controller method. I want to use the Authorize attribute.
// Auth Controller
[HttpGet("GetUsers")]
[Authorize(Roles = "admin")]
public ActionResult GetUsers()
{
var users = _authRepository.GetUsers();
return Ok(users);
}
and Repository.cs
public List<User> GetUsers()
{
var users = _context.Users.ToList();
return users;
}
Question: Do I need to write a middleware to read each user role from JWT and a put that role to the Identity Principal Claims? Please share your experince. I will be glad to know your approch.
I am glad I solved this question I am sharing the complete middleware. In every request by the user the middleware will check the userRole that is embadded in JWT token middle point
xxxx.UserInformation.yyyyy
we will take that user information.Now we need to call this middleware when the application start by goint to Startup.cs
Now Go to controller and Put an attribute on Methods.If the Role is admin it will execute the method or else it will return 403 Status Code.
I wish this helped for everyone who will Work with Authentication and Authorization using JWT Authentication in asp.net core all versions.