(一)jwt作用分析以及在Startup.cs里面的基础配置
前后端分离后,登陆系统后生成一个token,然后将呢个token返给前端,前端每次都要带着这个token进行登陆,否则无法访问后端api接口,后端不用去对比,无需存储token,无需对比,后端自动会识别token是否正确,实现了无状态化的验证(无状态化验证)
但是当验证只能在单设备上登陆的时候,必须存储当前用户的最新token,要不然同一个账号就可以在多个设备上登陆了,呢种后端必须要存储生成的token
1:在业务层(controller层)nuget下载3.1.9版本
Microsoft.AspNetCore.Authentication.JwtBear
2:在底层jwt的基础帮助类里面nuget下载
System.IdentityModel.Tokens.Jwt
3:Startup.cs配置
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
//跨域配置
string corsUrls = "https://www.xx.yy,http://xxx.yyy.z.hh:xxxx",
if (string.IsNullOrEmpty(corsUrls))
{
throw new Exception("请配置跨请求的前端Url");
}
services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
builder.WithOrigins(corsUrls.Split(",")).AllowCredentials()
.AllowAnyHeader().AllowAnyMethod().WithExposedHeaders("Authorization");
});
});
//引用jwt的相关配置
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
SaveSigninToken = true,//保存token,后台验证token是否失效
ValidateIssuer = true,//是否验证Issuer签发人
ValidateAudience = true,//是否验证Audience受众
ValidateLifetime = true,//是否验证失效时间
ValidateIssuerSigningKey = true,//是否验证SecurityKey
ValidAudience = "pms.core",//受众
ValidIssuer = "pms.core.owner",//签发人,这两项和前面签发jwt的设置一致
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("BB3647441FFA4B5DB4E64A29B53CE525"))
};
//jwt验证失败
options.Events = new JwtBearerEvents()
{
OnChallenge = context =>
{
//此处代码为终止.Net Core默认的返回类型和数据结果,这个很重,必须
context.HandleResponse();
context.Response.Clear();
context.Response.ContentType = "application/json";
context.Response.StatusCode = 401;
context.Response.WriteAsync(new { message = "授权未通过", status = false, code = 401 }.Serialize());
return Task.CompletedTask;
}
};
});
}
4:在Startup.cs的Configure方法里面的 app.UseAuthorization();上面需要新增:app.UseAuthentication();(启用jwt的权限验证):
app.UseCors();//启用跨域
app.UseAuthentication();//启用jwt权限认证
app.UseAuthorization();
5:依赖得json帮助类
public static class Exeper {
public static string Serialize(this object obj, JsonSerializerSettings formatDate = null)
{
if (obj == null) return null;
formatDate = formatDate ?? new JsonSerializerSettings
{
DateFormatString = "yyyy-MM-dd HH:mm:ss"
};
return JsonConvert.SerializeObject(obj, formatDate);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现