Web Api JWT 令牌认证
Posted
技术标签:
【中文标题】Web Api JWT 令牌认证【英文标题】:Web Api JWT token Authentication 【发布时间】: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 请求会显示未经授权的错误。”。你是如何使用它的?您是否添加了授权标头? 是的。授权标头添加为承载令牌 【参考方案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)
【讨论】:
记录异常也会很有用。以上是关于Web Api JWT 令牌认证的主要内容,如果未能解决你的问题,请参考以下文章
ASP.NET Core Web Api之JWT刷新Token