Issue with JWT bearer authentication for Asp.net Web API 2

I am trying to secure my web api services using JWT bearer authentication with OWIN middle ware .

I am able to generate tokens but how ever when validating them they are getting rejected and 401 error is being issued by the service .

Here is my code :

StartUp Class:

[assembly: OwinStartupAttribute(typeof(RetailerAPI.App_Start.Startup))]
namespace RetailerAPI.App_Start
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureOAuthTokenConsumption(app);
        }

        private void ConfigureOAuthTokenConsumption(IAppBuilder app)
        {

            app.UseJwtBearerAuthentication(
              new JwtBearerAuthenticationOptions
              {
                  AllowedAudiences = new[] { "RetailerClient" },


                  TokenValidationParameters = new TokenValidationParameters
                  {
                      ValidateLifetime = false,
                      ValidateAudience = false,
                      RequireExpirationTime = false,
                      IssuerSigningKey = new InMemorySymmetricSecurityKey(Encoding.UTF8.GetBytes("Very secure key for testing purpose"))


                  },


              }
            );
        }

    }
}   

Controller code

    [HttpPost]
    [Route("")]
    public IHttpActionResult Post([FromBody] CredentialModel model)
    {
        try
        {
            if(!ModelState.IsValid)
            {
                return BadRequest("Bad request.Username and Password required");
            }

            if(model.UserName.Equals("user",StringComparison.InvariantCultureIgnoreCase)&&model.Password.Equals("password"))
            {

                var claims = BuildClaims (model);
                var signingCredentials = GenerateSignInCredentials();
                var tokenProperties = BuildTokenProperties(claims, signingCredentials);

                return Ok(new
                {
                    token=new JwtSecurityTokenHandler().WriteToken(tokenProperties),
                    expirationTime= tokenProperties.ValidTo
                });
            }
            else
            {
                return BadRequest("Invalid user name and psssword");
            }
        }
        catch(Exception ex)
        {
            return BadRequest(ex.Message);
        }
    }


    private  SigningCredentials GenerateSignInCredentials()
    {
        var key = new InMemorySymmetricSecurityKey(Encoding.UTF8.GetBytes("Very secure key for testing purpose"));

        var SigningCredentials = new SigningCredentials(
            key,
            "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
            "http://www.w3.org/2001/04/xmlenc#sha256");

        return SigningCredentials;
    }

    private JwtSecurityToken BuildTokenProperties (Claim[] claims,SigningCredentials signingCredentials)
    {
        var tokenProperties = new JwtSecurityToken(
                 issuer: "RetailerAPI",
                 audience: "RetailerClient",
                 claims: claims,
                 expires: DateTime.UtcNow.AddMinutes(30),
                 signingCredentials: signingCredentials
                );
        return tokenProperties;
    }

please let me know what i am missing here

链接地址: http://www.djcxy.com/p/22402.html

上一篇: 这是什么样的承载身份验证令牌?

下一篇: 针对Asp.net Web API的JWT承载认证问题2