[英]How do I check whether a user is allowed to read / write a particular registry key?
[英]How does a webservice check whether a user is allowed to see an item?
我正在为移动应用程序(android)创建一个后端Web服务(asp.net core 2.0)。 应用程序的用户只能看到他的项目,我想在Web服务中进行检查。
在我的控制器中,我有这样的代码
[HttpGet( "{id}" )]
public async Task<IActionResult> Get( int id )
{
var item = _repository.GetItem( id );
if (!(await _authorizationService.AuthorizeAsync( User, item, nameof( IsAllowedToSeeRequirement ) )).Succeeded)
return BadRequest();
return new ObjectResult( item );
}
在某个地方,有一个IsAllowedToSeeRequirement
和一个AuthorizationHandler
实现来进行实际检查:
public class IsAllowedToSeeAuthorizationHandler : AuthorizationHandler<IsAllowedToSeeRequirement, Item>
{
protected override Task HandleRequirementAsync( AuthorizationHandlerContext context, IsAllowedToSeeRequirement requirement, Item item )
{
if (context.User.Identity.Name == item.Owner)
{
context.Succeed( requirement );
}
return Task.CompletedTask;
}
}
到目前为止,这很好,它可以工作,但是它涉及很多代码和间接操作, nameof
魔术字符串了(尽管通过nameof
减轻了...)
我可以写
[HttpGet( "{id}" )]
public IActionResult Get( int id )
{
var item = _repository.GetItem( id );
if (item.Owner != User.Identity.Name)
return BadRequest();
return new ObjectResult( item );
}
并跳过需求类,处理程序,处理程序的注册和需求。
在我读过的每一篇有关这种东西的教程中,总有这种处理程序。 因此,我认为采用费力的方法是有充分理由的,但是有人可以解释一下这可能是什么吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.