Files
Yi.Framework/Yi.Doc.Md/02.框架功能模块/12.Jwt鉴权.md
2023-12-15 23:44:35 +08:00

81 lines
2.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
## 简介
> 鉴权是用于解析用户的令牌,知道用户是否携带令牌,并且知道用户信息是谁
改鉴权使用的是微软Asp.NetCore扩鉴权扩展方式
程序模块已内置
``` cs
context.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ClockSkew = TimeSpan.Zero,
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = jwtOptions.Issuer,
ValidAudience = jwtOptions.Audience,
RequireExpirationTime = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOptions.SecurityKey))
};
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
if (!string.IsNullOrEmpty(accessToken))
{
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
});
```
## 如何使用
默认已经集成所以在使用方面可要求客户端添加标准的jwtbear头即可
swagger 接口文档中已集成直接输入jwttoken即可
![Alt text](../image/swaggerIndex.png)
我们采用的是HSA对称加密方式只需要具备密钥
对应的配置文件
``` json
//鉴权
"JwtOptions": {
"Issuer": "https://ccnetcore.com",
"Audience": "https://ccnetcore.com",
"SecurityKey": "zqxwcevrbtnymu312412ihe9rfwhe78rh23djoi32hrui3ryf9e8wfh34iuj54y0934uti4h97fgw7hf97wyh8yy69520",
"ExpiresMinuteTime": 86400
}
```
## Token如何来
那肯定是登录啊登录接口会返回Token
那如何制作Token直接上代码下面这个也是登录的创建token的方式
``` cs
/// <summary>
/// 创建令牌
/// </summary>
/// <param name="dic"></param>
/// <returns></returns>
private string CreateToken(Dictionary<string, object> dic)
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtOptions.SecurityKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var claims = dic.Select(x => new Claim(x.Key, x.Value.ToString())).ToList();
var token = new JwtSecurityToken(
issuer: _jwtOptions.Issuer,
audience: _jwtOptions.Audience,
claims: claims,
expires: DateTime.Now.AddSeconds(_jwtOptions.ExpiresMinuteTime),
notBefore: DateTime.Now,
signingCredentials: creds);
string returnToken = new JwtSecurityTokenHandler().WriteToken(token);
return returnToken;
}
```