【问题标题】:Porting JWT stateless authentication from Nancy 1.4.5 to 2.0.0将 JWT 无状态身份验证从 Nancy 1.4.5 移植到 2.0.0
【发布时间】:2019-05-10 23:50:34
【问题描述】:

我在 Nancy 1.4.5 中实现了 JWT 无状态身份验证,它曾经运行良好。 将我的项目移植到 Nancy 2.0.0,身份验证机制不再起作用。

在引导程序的 ApplicationStartup 方法中,我有:

    protected override void ApplicationStartup(IKernel container, IPipelines pipelines)
    {
        #region JWT authentication
        // JWT stateless authentication, see: https://foreverframe.net/nancy-meets-jwt-authentication/
        var secretKey = LocalConstants.Authorization.SecretKey;
        string cryptografyAlgorithm = LocalConstants.Authorization.CryptografyAlgorithm;
        string bearerDeclaration = LocalConstants.Authorization.HttpHeaderBearerDeclaration;
        var identityProvider = new IdentityProvider(secretKey, cryptografyAlgorithm, bearerDeclaration);
        var statelessAuthConfig = new StatelessAuthenticationConfiguration(identityProvider.GetUserIdentity);
        StatelessAuthentication.Enable(pipelines, statelessAuthConfig);
        #endregion
        ...

在运行时,客户端可以执行登录并正确获取 JWT。他们将 JWT 存储在后续请求的 HTTP 标头中。当后续请求到达服务器时,我的 identityProvider 的 GetUserIdentity 方法会读取 JWT 并正确返回有效的 ClaimsPrincipals。

在我的模块中

 this.RequiresAuthentication();

但是,抛出 Nancy.ErrorHandling.RouteExecutionEarlyExitException 异常,原因是“需要身份验证”,原因是“需要身份验证”,响应“未经授权的文本/html”,状态码为 Nancy.HttpStatusCode.Unauthorized。

将无状态身份验证移植到 Nancy 2.0.0 的正确方法是什么?

【问题讨论】:

    标签: authentication jwt nancy


    【解决方案1】:

    自己找到了解决方案:问题不在配置上,而在服务端使用 JWT 的方式上。作为参数传递给 StatelessAuthenticationConfiguration 对象(在我的示例中为identityProvider.GetUserIdentity)的函数应该返回一个身份已通过身份验证的 ClaimsIdentity。

    为此,传递一个非空、非空字符串作为 authenticationType 参数,如下所示:

    ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, "CustomAuthenticationType");
    

    在我之前的尝试中,我只是传递了声明,导致 claimIdentity 的 IsAuthenticated 属性评估为 False。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-18
      • 2011-11-12
      • 1970-01-01
      • 2021-08-05
      • 1970-01-01
      • 1970-01-01
      • 2017-08-15
      • 2020-05-16
      相关资源
      最近更新 更多