我正在开发一个应用程序,我需要实现自定义授权策略。 场景:用户只能在受雇的公司上发出GET请求。
到目前为止,我想出了下面的代码。我不喜欢的是在授权策略中以这种方式companyId
获取_httpContextAccessor.HttpContext.GetRouteData()?.Values["companyId"]
参数,因为将来更改companyId
参数名称可能会很困难,因为它将不可见在控制器方面,此参数也用于授权策略中。
有更好的方法吗?
[HttpGet("{companyId}")]
[Authorize(Policy = "UserEmployedInCompany")]
public ActionResult<CompanyReadDto> GetOne(int companyId)
{
var company = _repository.GetRepository<Company>().Get(companyId);
if (company == null)
{
return NotFound();
}
return _mapper.Map<CompanyReadDto>(company);
}
protected override async System.Threading.Tasks.Task HandleRequirementAsync(AuthorizationHandlerContext context,
UserEmployedInCompanyRequirement requirement)
{
var companyIdFromRoute = _httpContextAccessor.HttpContext.GetRouteData()?.Values["companyId"].ToString(); ;
int companyId = 0;
if (companyIdFromRoute is null || !int.TryParse(companyIdFromRoute, out companyId))
{
context.Fail();
}
var company = _repository.GetRepository<Company>()
.Find(x => x.Id == companyId, x => x.Employees).FirstOrDefault();
var currentUser = await _manager.GetUserAsync(context.User);
if (company != null && company.Employees.Exists(x => x.User == currentUser))
{
context.Succeed(requirement);
}
}