且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从 AuthorizationHandler .NET Core 获取参数

更新时间:2023-02-16 16:40:03

在您的处理程序中,您可以执行以下操作

In your handler you can do the following

var mvcContext = context.Resource as 
    Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext;

if (mvcContext != null)
{
    // Examine MVC specific things like routing data.
}

如果您想要参数值,那么授权属性片段会在绑定发生之前运行.相反,您将转到控制器内部的命令式调用.这基本上是基于资源的授权,您的参数是一个资源.

If you want parameter values then the authorize attribute pieces run before binding has taking place. Instead you would move to an imperative call, inside your controller. This is basically resource based authorization, your parameter is a resource.

您将授权服务注入您的控制器;

You would inject the authorization service into your controller;

public class DocumentController : Controller
{
    IAuthorizationService _authorizationService;

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

然后稍微不同地编写您的处理程序;

Then write your handler slightly differently;

public class DocumentAuthorizationHandler : AuthorizationHandler<MyRequirement, Document>
{
    public override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                MyRequirement requirement,
                                                Document resource)
    {
        // Validate the requirement against the resource and identity.

        return Task.CompletedTask;
    }
}

你可以看到这个处理程序接受一个文档,它可以是任何你喜欢的,可以是一个 ID 的整数,或者某种类型的视图模型.

You can see this handler takes a document, this can be whatever you like, be it an integer for an ID, or some type of view model.

然后您可以在 HandleRequirementAsync() 方法中访问它.

Then you have access to it inside your HandleRequirementAsync() method.

最后,一旦绑定发生,您将在控制器中调用它;

Finally, you'd call it from within your controller, once binding has taken place;

if (await authorizationService.AuthorizeAsync(
    User, 
    document,     
    yourRequirement))
{
}