c# - 检查 Action Controller 中的授权策略

标签 c# asp.net-core-webapi

因为 API 是与管理员和用户共享的。所以如果用户 ID 不等于参数,我想检查操作中的策略。

为简化起见,此应用程序使用 jwt token 作为访问 token 。所以现在有 2 个角色,它是 UserAdmin。因此,我根据此角色的声明添加了策略。下面是我如何在 startup.cs

中生成策略
public static IServiceCollection AddCustomAuthorizationPolicy(this IServiceCollection services) 
{
    services.AddAuthorization(options = >options.AddPolicy("UserOnly", policy = >policy.RequireClaim(CustomClaimTypes.UserManagement, "User", "Admin")));
    services.AddAuthorization(options = >options.AddPolicy("RequireAdmin", policy = >policy.RequireClaim(CustomClaimTypes.UserManagement, "Admin")));

    return services;
}

UserOnly 允许这两种角色。 RequireAdmin 仅限管理员。

这是我当前用于更改密码的 API

[HttpPost("{id}/change-password")]
[Authorize(Policy = "RequireAdmin")]
public async Task <IActionResult> ChangePassword([FromRoute] string id, [FromBody] UserChangePasswordViewModel model) 
{
    
    //This authorize filter require admin.
    //But I also want allow user to access
    
    var user = await _userManager.FindByIdAsync(id);

    if (user == null) return BadRequest("User not found");
    
    //My business logic here

}

所以我更改为允许两个角色访问它的 UserOnly

[HttpPost("{id}/change-password")]
[Authorize(Policy = "UserOnly")]
public async Task < IActionResult > ChangePassword([FromRoute] string id, [FromBody] UserChangePasswordViewModel model) 
{
    var getCurrentUserId = _identityService.GetUserIdentity();
    
    var user = await _userManager.FindByIdAsync(id);

    if (user == null) return BadRequest("User not found");
    
    if(getCurrentUserId != id)
    {
        //Check if this user is admin
        if(!isAdmin) //<-- Here I want to check the policy
        {
            //Response 403 forbidden
            
        }
    }

    //My business logic here

}

但我不太确定如何检查操作中的策略。有更好的建议吗?还是需要使用 HttpContext.User 来查找声明并检查值?

最佳答案

您可以通过在 Controller 中依赖 IAuthorizationService 并调用 IAuthorizationService.AuthorizeAsync 来做出动态策略决策。方法。一些虚构 Controller 的示例:

private readonly IAuthorizationService _authorizationService;

public MyController(IAuthorizationService authorizationService) 
{
    _authorizationService = authorizationService;
}

[HttpPost("{id}/protected-action")]
public async Task <IActionResult> SomeDynamicallyProtectedAction() 
{
    var isAdminEvaluationResult =
        await _authorizationService.AuthorizeAsync(User, null, "RequireAdmin");

    if (!isAdminEvaluationResult.Succeeded)
    {
        return Forbid();
    }

    // ...continue processing the request
}

关于c# - 检查 Action Controller 中的授权策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62559220/

相关文章:

c# - 什么 nhibernate 映射用于实体中的 string[]?

asp.net-mvc - 由于请求正文太大,大文件上传到 ASP.NET Core 3.0 Web API 失败

asp.net-core - Asp.net core web api - 扩展属性路由生成

c# - 是否可以将 WPF RichTextBox 中的文本设为 "zoom"?

c# - 是否有可能让 Visual Studio 或 Resharper 以不同的颜色突出显示枚举?

c# - 我可以通过调用代码调用类的基构造函数吗?

asp.net-core - ASP.NET core后台服务通过signalR发送数据

c# - Windows Forms .NET 中的 DataGridViewRow 线程安全

c# - SaveChangesAsync 只工作一次,然后总是失败

authentication - 如何解决postman调用.Net API时出现401未经授权的错误