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
关于博主:一本正经写程序&不务正业搞事情
版权声明:欢迎分享,转载请注明出处。
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!

posted @   码农搞事情  阅读(392)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
0
0
关注
跳至底部
点击右上角即可分享
微信分享提示