1、配置Setup
public void ConfigureServices(IServiceCollection services) { services.Configure<JwtIssuerOptions>(options => { options.Issuer = "SimpleServer"; options.Audience = "http://localhost"; options.SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes("12345678901234567890")), SecurityAlgorithms.HmacSha256); }); services.AddControllersWithViews(); }
2、生成JWT的输出token
var claims = new[] { new Claim(ClaimTypes.Name, "Celon"), new Claim(ClaimTypes.Role, "Admin") }; var option = _options.Value; var token = new JwtSecurityToken ( issuer: option.Issuer, audience: option.Audience, claims: claims, expires: DateTime.Now.AddMinutes(60), signingCredentials: option.SigningCredentials ); var outputToken = new JwtSecurityTokenHandler().WriteToken(token);
3、解析token
var jwt = new JwtSecurityToken(token);