how to check if the user is authorize to access page based on its role

I have a web application where front-end is reactjs and backend is asp.net core, I want to allow access the page based on the user roles. I have implemented the authorization in react but for security purpose need to perform authorization on server side.

I have a web application where front-end is reactjs and backend is asp.net core, I want to allow access the page based on the user roles.

I have implemented the authorization in react but for security purpose need to perform authorization on server side.

I have tried the [Authorize(Roles = "Administrator")] but that will not work since I am reusing the controller(common for all user) for different role and also I am not returning the view since I am working with react, so I need help in approach to implement the authorization part on asp.net core (role based)

5

2 Answers

If you really want to use one action per use case for all roles, you may consider using ControllerBase.HttpContext:

 [HttpGet("[action]")] [Authorize(Roles = "Administrator,User")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] public async Task<IActionResult> GetSomething() { var userRoles = this.HttpContext.User.Claims.Where(claim => claim.Type == System.Security.Claims.ClaimTypes.Role).Select(claim => claim.Value).ToList(); if (!userRoles.Any()) return Unauthorized(); return await GetSomethingDependingOnGivenRoles(userRoles); } 

You may use also extension for that:

public static class ControllerBaseExtensions { public static List<string> GetRoles(this ControllerBase controller) { return controller.HttpContext.User.Claims.Where(claim => claim.Type == System.Security.Claims.ClaimTypes.Role).Select(claim => claim.Value).ToList(); } } 

so you can then use it like this:

 [HttpGet("[action]")] [Authorize(Roles = "Administrator,User")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] public async Task<IActionResult> GetSomething() { var userRoles = this.GetRoles(); if (!userRoles.Any()) return Unauthorized(); return await GetSomethingDependingOnGivenRoles(userRoles); } 

Once approach is to have different actions for each role

[Authorize(Roles = "Administrator")] public IActionResult Action() {} 
1

ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJobG9saWiFd3yOoaawZaSkeqS0xJyiZqGWYsGpsYyuqp6qXZ7Abq3UrZ%2Boqpmvsm7AzmaYnJuVqMBuvMCgnGaakaiypXnOp2SirKNiv7C4xA%3D%3D

 Share!