【问题标题】:Validating Node.Js JWT token in asp.net/Authorize在 asp.net/Authorize 中验证 Node.Js JWT 令牌
【发布时间】:2017-08-11 15:48:15
【问题描述】:

我正在将我的 asp.net 服务拆分为多个微服务。作为一个流程,我使用 Node.Js 创建了我的身份服务,它使用 JWT 作为令牌。

现在我想在 C# 中使用此令牌,以便我的所有 [Authorise] 属性都使用此令牌并允许访问。

我查看了许多实现,但无法使其正常工作。由于 JWT 是标准实施,我不明白为什么这不起作用。

这是我的 C# 代码

 public void ConfigureAuth(IAppBuilder app)
 {
            var issuer = "myorg/identity2";
            string audienceId = ConfigurationManager.AppSettings["as:AudienceId"];
            byte[] audienceSecret = TextEncodings.Base64Url.Decode
            ("xfecrrt7CV");

            // Api controllers with an [Authorize] attribute will be validated with JWT
            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
                {
                    AuthenticationMode = AuthenticationMode.Active,
                    AllowedAudiences = new[] { audienceId },
                    IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                    {
                        new SymmetricKeyIssuerSecurityTokenProvider(issuer, audienceSecret)
                    }
                });

但是,每次我尝试访问受保护的方法时都会收到此错误。

{"Message":"Authorization has been denied for this request."}

这里有什么我遗漏的吗?如何将声明身份添加到此?

【问题讨论】:

  • 您确定此密钥xfecrrt7CV 与用于签名的密钥相同并且是base64url 编码的吗?
  • 令牌在标头中作为不记名令牌正确传递。我在jwt.io 上测试了令牌,如果我不选择“秘密 base64 编码”,它会得到正确验证。我尝试使用 UTF8、Unicode 编码将其转换为字节数组。但它不起作用。
  • 那么错误就在这里byte[] audienceSecret = TextEncodings.Base64Url.Decode("xfecrrt7CV"); 你正在尝试base64url 解码一个不是的字符串。你试过Encoding.UTF8.GetBytes("xfecrrt7CV");吗?
  • 是的,我确实尝试过 Encoding.UTF8.GetBytes("xfecrrt7CV")
  • 发行者是 NodeJS 端的 api 端点吗?你能告诉我们你是如何为那条路线声明控制器的吗?使用 express 你应该像这样注册一个中间件: app.use('/myorg/identity2', expressJwt({secret: secret}));以便请求包含令牌

标签: asp.net node.js jwt


【解决方案1】:

终于解决了。我的一位朋友调试了 Identity 源代码,并建议增加密钥长度。增加密钥长度后,我能够验证令牌

【讨论】:

  • 将修改后的代码贴在这里并标记为正确答案,以帮助其他可以找到该帖子的人。
猜你喜欢
  • 2019-10-20
  • 2018-08-30
  • 2020-08-22
  • 2020-09-04
  • 2020-07-01
  • 2023-03-15
  • 2019-06-23
  • 2021-12-17
  • 2017-07-27
相关资源
最近更新 更多