jwt

JWT
Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准((RFC 7519).该token被设计为紧凑且安全的,特别适用于分布式站点的单点登录(SSO)场景

401 未授权
403 禁止访问

传统的Session登录,有状态登录
用户登录后,用户信息保存在Session中。
CSRF: 因为是基于cookie来进行用户识别的, cookie如果被截获,用户就会很容易受到跨站请求伪造的攻击。

JWT无状态登录。
Post api/login 创建session,通过cookie传递session ID
请求携带cookie,并保护session ID

post api/login 使用密码加密JWT,返回jwt,保存在cookie中
请求携带jwt,使用相同的密码验证jwt。

jwt的原理:
无状态,token一经发布则无法取消
明文传递,token安全性低。https

--具体使用
1,引用jwt包 Microsoft.AspNetCore.Authentication.JwtBearer
2, 配置文件加相关资源配置
"Authentication": {
"Secrekey": "suibainzifuchuang",
"Issure": "fakeXieCheng.com",
"Audience": "fakeXieCheng.com"
},
3,生成token返回
public dynamic Login([FromBody] LoginDto loginDto)
{
// 1验证用户名和密码

// 2创建jwt
// header
var signingAlgorithm = SecurityAlgorithms.HmacSha256;
// payload
var claims = new[]
{
// sub
new Claim(JwtRegisteredClaimNames.Sub,"fake_user_id")
};
// signiture
var secretByte = Encoding.UTF8.GetBytes(_configuration["Authentication:Secrekey"]);
var signingKey = new SymmetricSecurityKey(secretByte);
var signingCredentials = new SigningCredentials(signingKey, signingAlgorithm);

var token = new JwtSecurityToken(
issuer: _configuration["Authentication:Issure"],
audience: _configuration["Authentication:Audience"],
claims,
notBefore: DateTime.UtcNow,
expires: DateTime.UtcNow.AddDays(1),
signingCredentials
);

var tokenStr = new JwtSecurityTokenHandler().WriteToken(token);
return tokenStr;
}
4,如何使用token,在core中。
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
// jwt的依赖注入
var secretByte = Encoding.UTF8.GetBytes(Configuration["Authentication:Secrekey"]);
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = Configuration["Authentication:Issure"],
ValidateAudience = true,
ValidAudience = Configuration["Authentication:Audience"],
ValidateLifetime = true,
IssuerSigningKey = new SymmetricSecurityKey(secretByte)
};
});
在需要的action中,加
[Authorize]//添加权限
5,则查询时需要携带参数
[{"key":"Authorization","value":"bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJmYWtlX3VzZXJfaWQiLCJuYmYiOjE2MzE2MzM4NjksImV4cCI6MTYzMTcyMDI2OSwiaXNzIjoiZmFrZVhpZUNoZW5nLmNvbSIsImF1ZCI6ImZha2VYaWVDaGVuZy5jb20ifQ.9EFhCMvdEhgAIExvQGo4vU9UOpHYWzdx8Dz_4VXL0YM","description":"","type":"text","enabled":true}]








posted @ 2021-09-14 23:50  vba是最好的语言  阅读(137)  评论(0编辑  收藏  举报