1.引入包
NuGet获取Microsoft.AspNetCore.Authentication.JwtBearer
2.获取token工具类
public class JwtTokenUtil
{
public string GetToken(string name)
{
// push the user’s name into a claim, so we can identify the user later on.
var claims = new[]
{
new Claim(ClaimTypes.Name,name),
//new Claim(ClaimTypes.Role, admin)//在这可以分配用户角色,比如管理员 、 vip会员 、 普通用户等
};
//sign the token using a secret key.This secret will be shared between your API and anything that needs to check that the token is legit.
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Appsettings.app(new string[] { "Authentication", "SecretKey" }))); // 获取密钥
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); //凭证 ,根据密钥生成
//.NET Core’s JwtSecurityToken class takes on the heavy lifting and actually creates the token.
/**
* Claims (Payload)
Claims 部分包含了一些跟这个 token 有关的重要信息。 JWT 标准规定了一些字段,下面节选一些字段:
iss: The issuer of the token,token 是给谁的 发送者
aud: 接收的
sub: The subject of the token,token 主题
exp: Expiration Time。 token 过期时间,Unix 时间戳格式
iat: Issued At。 token 创建时间, Unix 时间戳格式
jti: JWT ID。针对当前 token 的唯一标识
除了规定的字段外,可以包含其他任何 JSON 兼容的字段。
* */
var token = new JwtSecurityToken(
issuer: Appsettings.app(new string[] { "Authentication", "Issuer" }),
audience: Appsettings.app(new string[] { "Authentication", "Audience" }),
claims: claims,
expires: DateTime.Now.AddMinutes(double.Parse(Appsettings.app(new string[] { "Authentication", "Expires" }))),
signingCredentials: creds
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
3.创建拓展方法
public static class JwtTokenSetup
{
public static void AddJwtTokenSetup(this IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,//是否验证Issuer
ValidateAudience = true,//是否验证Audience
ValidateLifetime = true,//是否验证失效时间
ValidateIssuerSigningKey = true,//是否验证SecurityKey
ValidAudience = Appsettings.app(new string[] { "Authentication", "Audience" }),//Audience
ValidIssuer = Appsettings.app(new string[] { "Authentication", "Issuer" }),//Issuer,这两项和前面签发jwt的设置一致
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Appsettings.app(new string[] { "Authentication", "SecretKey" })))//拿到SecurityKey
};
});
}
}
4.Startup.cs 配置注册jwt
public void ConfigureServices(IServiceCollection services)
{
//注册jwttoken
services.AddJwtTokenSetup();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseSession();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseCors("allowCors");
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
5.LoginController
标记控制器是否需要验证jwttoken
[AllowAnonymous] //不需要 验证
[Authorize] //必须请求头携带token