Web Api JWT令牌认证

时间:2018-11-29 10:34:24

标签: c# authentication jwt token

我正在尝试创建和使用jwt令牌。令牌已成功生成,但使用该令牌进行POST请求,则会显示未经授权的错误。

我的startup.cs看起来像这样:

public void Configuration(IAppBuilder app)
{
    ConfigureAuth(app);
}

public void ConfigureAuth(IAppBuilder app)
{

    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(ConfigurationManager.AppSettings["JWTTokenKey"]));

    var signInCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);

    app.UseJwtBearerAuthentication(
        new JwtBearerAuthenticationOptions
        {
            //AuthenticationMode = AuthenticationMode.Active,
            TokenValidationParameters = new TokenValidationParameters()
            {
                ValidAudience = ConfigurationManager.AppSettings["Application"],
                ValidIssuer = ConfigurationManager.AppSettings["Application"],
                IssuerSigningKey = key
            }
        });
}

LoginController

public class LoginController : ApiController
{
    [HttpPost]
    [Route("api/v1/Login/Signin")]
    public IHttpActionResult Signin([FromBody] LoginModel login)
    {
        var claims = new[] { new Claim("UserName", login.UserName) };
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(ConfigurationManager.AppSettings["JWTTokenKey"]));
        var signInCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);
        var jwt = new JwtSecurityToken(
                issuer: ConfigurationManager.AppSettings["Application"],
                audience: ConfigurationManager.AppSettings["Application"],
                expires: DateTime.Now.AddMinutes(5),
                claims: claims,
                signingCredentials: signInCredentials
            );
        var token = new JwtSecurityTokenHandler().WriteToken(jwt);
        return Json(new
        {
            access_token = token,
            expires = Convert.ToString(jwt.ValidTo)
        });
    }

    [Authorize]
    [HttpPost]
    public int Register(int id)
    {
        return 1;
    }

    [HttpPost]
    public void TestPost([FromBody]string value)
    {
    }

    public class LoginModel
    {
        public string UserName { get; set; }
        public string Password { get; set; }
    }
}

如何使用生成的jwt令牌在LoginController中调用Register方法。预先感谢。

1 个答案:

答案 0 :(得分:1)

try
{
  using ( HttpClientHandler handler = new HttpClientHandler())
  {
    using(HttpClient c = new HttpClient(handler))
    {
      c.DefaultRequestHeaders.Add("Authorization","Bearer " + UsersJwtToken);
      //Get the token and attach it here.
      //This is how you add jwt token to your requests.
      //After this you can just make requests to the API.
     
    }

  }
}
catch(Exception ex)
{
}