JWT token not accepted by Web APi2 authentication

2019-05-15 23:50发布

问题:

I followed the tutorial but it's seems not working properly with JWT, but it was ok for basic authentication.

I downloaded and installed JwtAuthForWebAPI. I also generated JWT token and trying to do a API call but error is HTTP/1.1 401 Unauthorized.

Do I have to implement/modify anything to transfer claims from JWT to Thread.CurrentPrincipal & HttpContext.CurrentPrincipal?

My code is quite simple: 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=" 
  />

Call example

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

回答1:

Haha, I found error in the book's tutorial:)

There was a wrong JWT value in my example:) The proper call should looks like this. I had to recreate JWT token manually.

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