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 { ***** }