简体   繁体   English

如何在.NET Core的基于策略的授权中添加应用逻辑

[英]How to add application logic in policy based authorization in .NET Core

I have the current setup working but I get an error like this:我有当前的设置工作,但我收到这样的错误:

An attempt was made to use the context instance while it is being configured. 
A DbContext instance cannot be used inside 'OnConfiguring' since it is still being configured at this point. 
This can happen if a second operation is started on this context instance before a previous operation completed. 
Any instance members are not guaranteed to be thread safe. 

I have created IAuthorizationRequirement我创建了IAuthorizationRequirement

public class ValidGroupsRequirement : IAuthorizationRequirement
{
    private IAuthenticationService _authenticationService;
    public async Task<bool> ValidateAccess(IAuthenticationService authenticationService, List<string> groups)
    {
        _authenticationService = authenticationService;
        var result = await _authenticationService.AllGroupsExist(groups);
        return result;
    }
}

Also AuthorizationHandler还有AuthorizationHandler

public class GroupsValidationHandler : AuthorizationHandler<ValidGroupsRequirement>
{
    private readonly IAuthenticationService authenticationService;
    
    public GroupsValidationHandler(IAuthenticationService authenticationService)
    {
        this.authenticationService = authenticationService;
    }
    
    protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, ValidGroupsRequirement requirement)
    {
        var userGroups = context.User.FindAll("groups").Select(X => X.Value).ToList();
        var result = await requirement.ValidateAccess(authenticationService, userGroups);
        if (result)
        {
            context.Succeed(requirement);
        }
        else
        {
            context.Fail();
            var filterContext = context.Resource as DefaultHttpContext;
            var response = filterContext.HttpContext.Response;
            response.OnStarting(async () =>
            {
                filterContext.HttpContext.Response.StatusCode = 401;
            });
        }
    }
}

And I have registered them in Program.cs我已经在Program.cs中注册了它们

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("ValidateGroups", policy =>
    {
        policy.RequireAuthenticatedUser();
        policy.AddRequirements(new ValidGroupsRequirement());
    });
    options.InvokeHandlersAfterFailure = false;
});

builder.Services.AddScoped<IAuthenticationService, AuthenticationService>();

I have the error in the authentication service.我在身份验证服务中遇到错误。

Is it possible not to dispose it correctly since I am passing it to the requirement?因为我将它传递给要求,是否有可能不正确处理它?

I know there is a way to create a handler without an requirement, but context.Succeed() method accepts requirement only.我知道有一种方法可以在没有要求的情况下创建处理程序,但是 context.Succeed() 方法只接受要求。 How should I then register it in program.cs我应该如何在program.cs中注册它

Thank you谢谢

I didn't have your problem after testing, everything works fine except that I cannot use _authenticationService.AllGroupsExist() , so I directly output the result as true to replace your output. IAuthenticationService does not seem to provide this method, did you customize it?测试后没有遇到你的问题,一切正常,只是不能使用_authenticationService.AllGroupsExist() ,所以我直接output resulttrue来替换你的IAuthenticationService好像没有提供这个方法,你自定义了吗?

I registered Handler according to this document :我根据这个文档注册了Handler程序:

builder.Services.AddTransient<IAuthorizationHandler, GroupsValidationHandler>();

Then authorize certain operations:然后授权某些操作:

[Authorize(Policy = "ValidateGroups")]

And everything is executing normally.一切都在正常执行。

Can you provide a minimal example that reproduces the problem?您能否提供一个重现该问题的最小示例?

You can check this document and this post , it should help you.您可以查看此文档此帖子,它应该对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在ASP.NET Core中修复基于策略的授权 - How to fix policy based authorization in ASP.NET Core 基于JWT的.Net MVC核心策略的授权 - .Net MVC Core Policy based authorization with JWT 如何创建包含2x逻辑规则的ASP.NET Core授权策略? - How to create an ASP.NET Core Authorization Policy that contains 2x logic rules? 基于ASP.NET核心自定义策略的授权 - 不清楚 - ASP.NET Core Custom Policy Based Authorization - unclear ASP.NET Core中基于策略的授权(异步) - Policy-based authorization in ASP.NET Core (async) asp.net core 2.0 - 基于声明和策略的授权 - asp.net core 2.0 - Claims and policy based Authorization 基于策略的授权不适用于asp.net核心 - Policy based Authorization not working in asp.net core 如何访问 ASP.NET Core 2 使用 AuthorizationHandlerContext 的自定义基于策略的授权中的当前 HttpContext - How to access current HttpContext in ASP.NET Core 2 Custom Policy-Based Authorization with AuthorizationHandlerContext 如何向 ASP.NET CORE 授权策略添加 OR 子句? - How can I add an OR clause to a ASP.NET CORE Authorization Policy? 如何在.NET Core中正确设置WEB API的策略授权 - How to correctly setup Policy Authorization for WEB API in .NET Core
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM