在 Hot Chocolate 中使用授权时未调用 HandleRequirementAsync

HandleRequirementAsync not being called when using authorization in Hot Chocolate

你好,

我正在尝试在 Hot Chocolate graphql 服务器中实施基于策略的授权。 我在看他们的 documentation and also referring to Microsoft's guide

我想要达到的目标

我希望在调用 User query 时调用 HandleRequirementAsync()

我做了什么
  1. 我在ConfigureServices
  2. 注册授权和User Policy
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHttpContextAccessor();
            services.AddAuthorization(options =>
            {
                options.AddPolicy("UserPolicy",
                policy => policy.Requirements.Add(new UserRequirement()));
            });


            services.AddSingleton<Query>();

            services.AddSingleton<IAuthorizationHandler, UserAuthorizationHandler>();

            services.AddSingleton(typeof(IUserRepo), typeof(UserRepo));
            services.AddSingleton(typeof(IBookRepository), typeof(BookRepository));

            services.AddGraphQL(
                SchemaBuilder.New()
                    .AddAuthorizeDirectiveType()
                    .AddType<UserType>()
                    .AddType<BookType>()
                    .AddQueryType<Query>());
        }
  1. 我有 User requirement classhandler
 public class UserAuthorizationHandler : AuthorizationHandler<UserRequirement, IResolverContext>
    {
        private IHttpContextAccessor _accessor;

        public UserAuthorizationHandler([Service] IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }

        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, UserRequirement requirement,
            IResolverContext resource)
        {
            context.Succeed(requirement);
            return Task.CompletedTask;
        }
    }

    public class UserRequirement : IAuthorizationRequirement
    {
    }
  1. 我声明了一个字段需要策略授权。
    public class UserType
        : ObjectType<User>
    {
        protected override void Configure(IObjectTypeDescriptor<User> descriptor)
        {
            descriptor.Field(t => t.Name).Type<NonNullType<StringType>>().Authorize("UserPolicy");
            descriptor.Field(t => t.Id).Type<NonNullType<StringType>>();
        }
    }

问题

当运行这段代码。我希望 HandleRequirementAsync 会被调用。此方法应始终成功。但是,在请求用户时。实际发生的是该方法未被调用,请求立即被拒绝,响应如下:

{
  "errors": [
    {
      "message": "The current user is not authorized to access this resource.",
      "locations": [
        {
          "line": 3,
          "column": 5
        }
      ],
      "path": [
        "user",
        "name"
      ],
      "extensions": {
        "code": "AUTH_NOT_AUTHENTICATED"
      }
    }
  ]
}

我刚刚遇到了类似的问题。就我而言,我必须确保在

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

我有

app.UseAuthentication();
app.UseAuthorization();

然后

app.UseWebSockets()
                .UseGraphQL("/graphql")
                .UsePlayground("/graphql")
                .UseVoyager("/graphql");