我有一个前端reactjs
和后端的 Web 应用程序asp.net core
,我想允许根据用户角色访问页面。
我已经在反应中实现了授权,但出于安全目的需要在服务器端执行授权。
我已经尝试过[Authorize(Roles = "Administrator")]
但是这不起作用,因为我将控制器(所有用户通用)重用于不同的角色,而且我没有返回视图,因为我正在使用 react,所以我需要帮助来实现授权部分在asp.net core
(基于角色)
如果您真的想为所有角色使用每个用例的一个操作,您可以考虑使用 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);
}
您也可以使用扩展名:
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();
}
}
所以你可以像这样使用它:
[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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句