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

时间:2017-11-17 13:41:50

标签: authentication asp.net-web-api jwt owin

我正在尝试使用使用OWIN 中间件的JWT承载身份验证来保护我的网络API服务。

我能够生成令牌,但如何验证它们时,它们会被拒绝,服务会发出401错误

这是我的代码:

启动类:

[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"))


                  },


              }
            );
        }

    }
}   

控制器代码

    [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;
    }

请让我知道我在这里缺少什么

1 个答案:

答案 0 :(得分:0)

我想您需要确保令牌是通过Authorization标头传递的。

此外,令牌本身必须以Bearer关键字开头:

let options_ : any = {
    body: content_,
    observe: "response",
    responseType: "blob",
    headers: new HttpHeaders({
        "Content-Type": "application/json", 
        "Accept": "application/json",
        "Authorization": "Bearer " + localStorage.getItem('token')
    })
};

有关更多详细信息,请参见my answer