为过期令牌添加身份验证错误处理

问题描述

我正在使用带有 .net Core 3.1 的 graphQl Hot Chocolate V11 我对令牌过期的识别没有问题,只是将该问题转发回请求者才是问题所在。

我正在尝试向我的请求添加一些身份验证,但是当授权令牌因时间到期或什至任何其他潜在原因导致令牌无效而不再有效时,我遇到了响应问题.

enter image description here

enter image description here

但是当我抛出异常以尝试告诉请求者他们的令牌已过期时,它不会通过 Hot Chocolate IErrorFilter 样式返回,就像服务器错误一样。

enter image description here

如果有更好的内置方法来检查这些事情并正确响应请求者,有人可以帮我吗?我会莫尔斯认为错误应该像最后一个屏幕截图的格式一样显示,我猜是热巧克力 IErrorFilter 响应(该屏幕截图中的错误是如果我没有正确处理用户未通过身份验证时看到的,因为我没有当前用户添加到查询期望的上下文中)

enter image description here

解决方法

semi 唯一起作用的是创建这样的异常,它允许我添加正确的错误代码,但仍然不返回作为查询的答案

throw new GraphQLRequestException(ErrorBuilder.New()
                                .SetMessage(ExpiredTokenString)
                                .SetCode(ExpiredTokenCode)
                                .Build());
,

我不知道这是否会解决您的问题,但它可能是一种可接受的解决方法,并且会产生不同的结果。使用它来强制执行有效的登录安全策略:

            // Add policy in Startup.cs
            services.AddAuthorization(options =>
            {
                options.AddPolicy("LoggedInPolicy",Policies.LoggedInPolicy);
            });

然后添加一个策略类

    public class Policies
    {
        /// <summary>
        /// Requires the user to be logged in
        /// </summary>
        /// <param name="policy"></param>
        public static void MultiFactorAuthenticationPolicy(AuthorizationPolicyBuilder policy)
        {
            policy.RequireAuthenticatedUser();
        }
    }

然后使用您的授权属性装饰适当的端点以应用策略

        /// <summary>
        /// Test 'hello world' endpoint
        /// </summary>
        /// <returns>The current date/time on the server</returns>
        [Authorize(Policy = "LoggedInPolicy")]
        public string Hello()
        {
            return DateTime.Now.ToString("O");
        }

您可能还需要将此添加到 GraphQL 配置中

SchemaBuilder.New()
  ...
  .AddAuthorizeDirectiveType()
  ...
  .Create();

(来自https://chillicream.com/docs/hotchocolate/v10/security/,不知道这有多少适用于 v11)

这可能与一些不同的错误处理程序有关。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...