有没有办法在没有身份验证 header 的请求中使用 Authorize 属性?

Is there a way to use the Authorize attribute with a request that does not have an authentication header?

我正在尝试将 API 从使用身份验证 header 进行身份验证转换为使用 JSON body 中的值进行身份验证。从现在开始我将收到的请求将不包含身份验证 header。它们将在 JSON 请求 body 的 body 中包含不记名令牌。我能够使用 OnMessageReceived 事件处理程序来解析令牌,但在我点击 OnMessageReceived 处理程序之前,我在输出中收到了一条授权失败消息。在通过身份验证处理程序之前,它似乎授权失败。至于AuthorizeAttribute,[Authorize][Authorize(AuthenticationSchemes = "Bearer")]我都试过了,都没有成功。

我没有在我的 setup.cs 中放置任何自定义授权策略,所以它使用默认的。在做了一些研究之后,我发现默认授权策略的唯一要求是 DenyAnonymousAuthorizationRequirement。我在下面包含了需求检查代码:


        /// <summary>
        /// Makes a decision if authorization is allowed based on a specific requirement.
        /// </summary>
        /// <param name="context">The authorization context.</param>
        /// <param name="requirement">The requirement to evaluate.</param>
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, 
                                                       DenyAnonymousAuthorizationRequirement requirement)
        {
            var user = context.User;
            var userIsAnonymous =
                user?.Identity == null ||
                !user.Identities.Any(i => i.IsAuthenticated);
            if (!userIsAnonymous)
            {
                context.Succeed(requirement);
            }
            return Task.CompletedTask;
        }

在我看来,如果没有授权 header,它会自动失败(这似乎可能是一个错误)。我尝试添加授权 header(同时具有有效令牌和过期令牌)并在 OnMessageReceived 处理程序中放置断点。结果是 HttpContext.User.Identity(identities 中的唯一身份),IsAuthenticated 值为 false。这与未经授权的请求结果匹配 header.

我的问题是在我的场景中是否可以使用 Authorize 属性。如果不是,是否需要创建授权过滤器?

事实证明,我使用的 .AddIdentityServerAuthentication() 根据 IdentityServer (https://github.com/IdentityServer/IdentityServer4/issues/4892) 现在已经过时了。切换到 .AddJwtBearer 解决了我的问题。授权开箱即用,正如预期的那样。