zoukankan      html  css  js  c++  java
  • 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
    {
      *****
    }
  • 相关阅读:
    Augular JS里的各种ng-
    JS笔记1
    JQuery实战学习--在dreamweaver 8中配置Jquery自动提示
    android 设置桌面背景图片适应屏幕大小
    canvas实现进度条!
    Javascript之Prototype
    Sql Server 之 for xml (path,raw,auto,root)
    MVC 知识点学习3(linq to sql)
    MVC 知识点学习2
    MVC 知识点学习1
  • 原文地址:https://www.cnblogs.com/fmp/p/jwt.html
Copyright © 2011-2022 走看看