JWT(Json Web Token)
jwt是一种用于身份验证的开放标准,他可以在网络之间传递信息,jwt由三部分组成:头部,载荷,签名。头部包含了令牌的类型和加密算法,载荷包含了用户的信息,签名则是对头部和载荷的加密结果。
jwt鉴权验证是指在用户登录成功后,服务器生成一个jwt令牌并返回给客户端,客户端在后续的请求中携带该令牌,服务通过令牌的签名来确定用户的身份和权限。这种方式可以避免在每个请求中都需要进行身份验证,提高了系统的性能和安全性。
jwt具有以下优点:
1.无状态:jwt令牌包含了所有必要的信息,服务器不需要再每个请求中都进行身份验证,避免了服务器存储会话信息的开销。
2.可扩展性:jwt令牌可以包含任意的信息,可以根据需要添加自定义的字段。
3.安全性:jwt令牌使用签名来保证数据的完整性和真实性,防止数据被篡改或伪造。
4.跨平台:jwt令牌是基于json格式的,可以再不同的变成语言和平台之间进行传递和解析。
如何在webapi中使用JWT?
1. 添加所需Nuget包:
Microsoft.AspNetCore.Authentication.JwtBearer
System.IdentityModel.Tokens.Jwt
2. 创建JwtOptions Model,在appsettings.json中添加配置
namespace CustomerCommunity.Common.SettingConfig
{
public class AuthenticationConfig
{
/// <summary>
/// 发布者
/// </summary>
public string Issuser { get; set; }
/// <summary>
/// 接收者
/// </summary>
public string Audience { get; set; }
/// <summary>
/// 密钥
/// </summary>
public string SecretKey { get; set; }
/// <summary>
/// 过期时间(s)
/// </summary>
public int ExpireSeconds { get; set; }
}
}
"AuthenticationConfig": {
"Issuser": "1234",
"Audience": "233333",
"SecretKey": "SecretKeySecretKeySecretKey",
"ExpireSeconds": 10
}
2. 添加IServiceCollection扩展方法
注入AuthenticationConfig,方便构造函数中通过IOptions<AuthenticationConfig>取值
public static void AddConfigure(this IServiceCo