JWT
https://github.com/jwt-dotnet/jwt
public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.SaveToken = true; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(configuration["Jwt:Key"])), ValidateLifetime = true, //validate the expiration and not before values in the token ClockSkew = TimeSpan.FromMinutes(1) //1 minute tolerance for the expiration date
ValidateIssuer = false, //不验证发行人
ValidateAudience = false //不验证授予人
};
options.Events = new JwtBearerEvents { OnChallenge = context => { context.HandleResponse(); var payload = JsonConvert.SerializeObject(new { msg = "请登录后再试", code = "4001" }); context.Response.ContentType = "application/json"; context.Response.StatusCode = StatusCodes.Status200OK; context.Response.WriteAsync(payload); return Task.CompletedTask; } }; }); }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseAuthentication(); }
string CreateUserToken(User user) { return new JwtBuilder() .WithAlgorithm(new HMACSHA256Algorithm()) //算法 .WithSecret(configuration["Jwt:Key"]) //secret //.AddClaim(JwtRegisteredClaimNames.Nbf, new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()) //生效时间 .AddClaim(JwtRegisteredClaimNames.Exp, DateTimeOffset.UtcNow.AddYears(1).ToUnixTimeSeconds()) //过期时间 .AddClaim(ClaimTypes.Sid, user.Id) .Encode(); }
public string GetUserIdFromToken(string token) { var payload = new JwtBuilder() .WithAlgorithm(new HMACSHA256Algorithm()) .WithSecret(configuration["Jwt:Key"]) .MustVerifySignature() .Decode<IDictionary<string, object>>(token); return payload == null || payload.Count == 0 ? null : payload["userId"]?.ToString(); }
[ApiController] [Authorize] public class HomeController : ControllerBase { ***** }
__EOF__
作 者:码农搞事情
出 处:https://www.cnblogs.com/fmp/p/jwt.html
关于博主:一本正经写程序&不务正业搞事情
版权声明:欢迎分享,转载请注明出处。
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。您的鼓励是博主的最大动力!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?