JWT 相关知识
C#中创建Token
// 创建一个token令牌
//创建声明数组
var claims = new Claim[]
new Claim(ClaimTypes.Name,"Youri"),
new Claim(JwtRegisteredClaimNames.Email,"youri@qq.com"),
new Claim(JwtRegisteredClaimNames.Sub,"1") //主题是声明 id
//实例化token对象
var token = new JwtSecurityToken(
claims:claims
//生成token
var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
return new string[] {jwtToken};
这样的token无效,无 数字签名跟加密算法
因此需要加上其他的代码使其有效:
同样,首先创建声明数组
//创建声明数组
var claims = new Claim[]
new Claim(ClaimTypes.Name,"Youri"),
new Claim(JwtRegisteredClaimNames.Email,"youri@qq.com"),
new Claim(JwtRegisteredClaimNames.Sub,"1") //主题是声明 id
//实例化token对象
var token = new JwtSecurityToken(
claims:claims
var token_simple = new JwtSecurityToken(
claims:claims
);
// 生成密钥(至少16位,可在application里面配置)
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Youri123456789123"));
var token = new JwtSecurityToken(
issuer: "http://localhost:5000",
audience: "http://localhost:5001";
claims: claims,
expires: DateTime.Now.Addhours(1),
signingCredientials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
);
// 生产token
var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
return new string[] {jwtToken};
获取token的方法:
//1
var jwtHandler = new JwtSecurityTokenHandler();
JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);
//2
var sub =User.FindFirst(d=>d.type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name")?.Value;
//3
var name = _accessor.HttpContext.User.Identity.Name;
var claims = _accessor.HttpContext.User.Claims;
var claimTypeVal = (from item in claims
where item.type == JwtRegisteredClaimNames.Email
select item.Value).Tolist();
使用:
////////首先转化为服务(AddJwtBearer)
services.AddAuthentication("Bearer")
.AddJwtBearer(o=>
o.TokenValidationParameters = tokenValidationParameters;
})
//// 然后这个服务对象经过中间件,添加到http context中
//在configure function中
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
///其余省略
app.UseAuthentication();
接着会赋值给HttpContext.user 对象
api的authorize 就是通过bearer token获取到对应的内容进行验证。
总结:
1、创建了一个claim的声明数组
2、实例化一个Tokenobj(包含基础信息),生成一个至少16位的密钥,
3、生成一个SecurtiyToken (包含TokenObj,expiredtime,密钥跟加密方法生成的Credential及一些其他参数)。