本文介绍如何在.net core中启用jwt authentication及生成token
JSON Web Token(缩写 JWT),一种跨域认证解决方案,它本身包含了认证信息,所以server无需再保存session,做到无状态和方便横向扩展。
JWT 的三个部分依次如下:
public Token GetAccessToken(string appID, string appSecret)
{
var key = System.Text.Encoding.ASCII.GetBytes("[secret]");
var handler = new JwtSecurityTokenHandler();
var descriptor = new SecurityTokenDescriptor()
{
Subject = new System.Security.Claims.ClaimsIdentity(
new Claim[]{
new Claim(ClaimTypes.Name, appID)
}
),
Expires = DateTime.UtcNow.AddSeconds(_setting.Expired),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256)
};
var token = handler.CreateToken(descriptor);
var access_token = handler.WriteToken(token);
public void ConfigureServices(IServiceCollection services)
{
var keyBytes = System.Text.Encoding.ASCII.GetBytes("[secret]");
// services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerDefaults.AuthenticationScheme;
})
.AddCookie(Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme)
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
{
IssuerSigningKey = new SymmetricSecurityKey(keyBytes),
ValidateIssuerSigningKey = true,
ValidateIssuer = false,
ValidateAudience = false
};
});
[Microsoft.AspNetCore.Authorization.Authorize]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
[HttpPost("[action]")]
public object GetUsers([FromBody] GetUsersModel searchModel)
{
}
}
将jwt放在post请求的header中:
Authorization: Bearer [jwt]
请求如上action,验证是否可以正常获取资料
原文:https://www.cnblogs.com/windchen/p/12484432.html