使用JwtAuthForWebAPI的Web APi2身份验证不接受JWT令牌

本文关键字:不接受 JWT 令牌 身份验证 APi2 JwtAuthForWebAPI Web 使用 | 更新日期: 2023-09-27 18:01:45

我遵循了教程,但它似乎不能正常使用JWT,但它可以用于基本身份验证。

我下载并安装了JwtAuthForWebAPI。我还生成了JWT令牌,并试图做一个API调用,但错误是HTTP/1.1 401 Unauthorized

我必须实现/修改任何东西从JWT转移索赔到线程。CurrentPrincipal,HttpContext.CurrentPrincipal吗?

我的代码很简单:global.asax.cs:

GlobalConfiguration.Configuration.MessageHandlers.Add(
    new JwtAuthenticationMessageHandler
    {
        AllowedAudience = reader.AllowedAudience,
        Issuer = reader.Issuer,
        SigningToken = builder.CreateFromKey(reader.SymmetricKey)
    });

web . config:

<configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
    <section name="JwtAuthForWebAPI" type="JwtAuthForWebAPI.JwtAuthForWebApiConfigurationSection"/>
  </configSections>
  <JwtAuthForWebAPI
    AllowedAudience="http://www.example.com"
    Issuer="corp"    
    SymmetricKey="cXdlcnR5dWlvcGFzZGZnaGprbHp4Y3Zibm0xMjM0NTY=" 
  />

调用例子

GET http://localhost:34669/api/v1/tasks/8 HTTP/1.1 
Host: localhost:34669 
Authorization: Bearer  eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJjb3JwIiwiYXVkIjoiaHR0cDovL3d3dy5leGFtcGxlLmNvbSIsIm5iZiI6MTQwMDU1Mzc1NywiZXhwIjoxNzE2MTcyOTU3LCJ1bmlxdWVfbmFtZSI6ImJob2dnIiwiZ2l2ZW5fbmFtZSI6IkJvc3MiLCJmYW1pbHlfbmFtZSI6IkhvZ2ciLCJyb2xlIjpbIk1hbmFnZXIiLCJKdW5pb3JXb3JrZXIiXX0.Ls73kz80rCaCNqzc3K32BVO9_LnJDL8c1g5AXKIzn8w

使用JwtAuthForWebAPI的Web APi2身份验证不接受JWT令牌

哈哈,我在书的教程中发现了错误:)

在我的例子中有一个错误的JWT值:)正确的调用应该是这样的。我必须手动重新创建JWT令牌。

GET http://localhost:34669/api/v1/tasks/8 HTTP/1.1 
Host: localhost:34669
Authorization: Bearer  eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1bmlxdWVfbmFtZSI6ImJob2dnIiwiZ2l2ZW5fbmFtZSI6IkJvc3MiLCJmYW1pbHlfbmFtZSI6IkhvZ2ciLCJyb2xlIjpbIk1hbmFnZXIiLCJTZW5pb3JXb3JrZXIiLCJKdW5pb3JXb3JrZXIiXSwiaXNzIjoiY29ycCIsImF1ZCI6Imh0dHA6Ly93d3cuZXhhbXBsZS5jb20iLCJleHAiOjE3NTIwNjgzNjAsIm5iZiI6MTQzNjQ0OTE2MH0.t1lK0ZEA_IZbdiiYeJuuLVeeh1CFSiodzmRPdmezv3c