使用JwtAuthForWebAPI进行Web APi2身份验证时不接受JWT令牌

时间:2015-07-09 12:34:04

标签: c# asp.net-web-api2 jwt

我遵循了教程,但它似乎与JWT无法正常工作,但它可以用于基本身份验证。

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

我是否必须实施/修改任何内容以将声明从JWT转移到Thread.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

1 个答案:

答案 0 :(得分:2)

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

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

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