【问题标题】:Web Api JWT token AuthenticationWeb Api JWT 令牌认证
【发布时间】:2019-05-01 09:31:58
【问题描述】:

我正在尝试创建和使用 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
            }
        });
}

登录控制器

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 方法。提前致谢。

【问题讨论】:

  • 您说“但使用该令牌进行 POST 请求会显示未经授权的错误。”。你是如何使用它的?您是否添加了授权标头?
  • 是的。授权标头添加为承载令牌

标签: c# authentication jwt token


【解决方案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)
{
}

【讨论】:

  • 记录异常也会很有用。
猜你喜欢
  • 1970-01-01
  • 2017-08-20
  • 2020-09-25
  • 2020-10-24
  • 2022-12-04
  • 1970-01-01
  • 1970-01-01
  • 2020-05-12
  • 2019-08-09
相关资源
最近更新 更多