写在前面
JWT(JSON Web Token)是一种开放标准, 由三部分组成,分别是Header、Payload和Signature,它以 JSON 对象的方式在各方之间安全地传输信息。通俗的说,就是通过数字签名算法生产一个字符串,然后在网络请求的中被携带到服务端进行身份认证,功能上来说和 SessionId 认证方式很像。
在.Net Core 中使用JWT 可以通过 NuGet 获取 Microsoft.AspNetCore.Authentication.JwtBearer 包。
另外JWT需要配置一个Key, 需要提前生成好;在上一篇中介绍过:
用keytool 生成JWT的RSA非对称密钥-CSDN博客
代码实现
appsettings.json 中的配置
{"Logging": {"LogLevel": {"Default": "Information","Microsoft.AspNetCore": "Warning"}},"AllowedHosts": "*","Jwt": {"Key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArLhdR+Df8J9jNN4xuF9eqtbmibTpLaj1Re/e2aCuCFtVTfDgKsHklSSC4O8Jq0cyEBKs/SGhP8DD3w9vgFuWbpUcoYsWAEaV0zjWtJtng+upcpa4VTgi2jLltht+ukTs3f5uUsAXQT8pbBLyBZEcKZ1AuvFZCasG6BYPOJSiypQIeCWo0nq4u3cyaX4C5qjdhacxtT7RVXtQ5nWnMQxP+Mq2mf5x/zWEcCDhPFM5w7ulkcGOoWSCA3lRMOFB7fX49shBLgKAkATsSEB+EtmpWdbyI1pbRMqteWPELMLEB8EuJ0IEI4LRC59rlh/aQYHmyZnAKR", // 密钥"Issuer": "rjcql", // 颁发者"Audience": "rjcql" // 接收者}
}
代码主体:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;var builder = WebApplication.CreateBuilder(args);builder.Services.AddAuthentication(options =>
{options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{o.TokenValidationParameters = new TokenValidationParameters{ValidIssuer = builder.Configuration["Jwt:Issuer"],ValidAudience = builder.Configuration["Jwt:Audience"],IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])),ValidateIssuer = true,ValidateAudience = true,ValidateLifetime = false,ValidateIssuerSigningKey = true};
});
builder.Services.AddAuthorization();var app = builder.Build();app.UseHttpsRedirection();
app.MapGet("/", () => "Hello everyone.");
app.MapGet("/security/getMessage", () => "Hello rjcql!").RequireAuthorization();
app.MapPost("/security/createToken",
[AllowAnonymous] (User user) =>
{if (user.UserName == "rjcql" && user.Password == "111111"){var issuer = builder.Configuration["Jwt:Issuer"];var audience = builder.Configuration["Jwt:Audience"];var key = Encoding.ASCII.GetBytes(builder.Configuration["Jwt:Key"]);var tokenDescriptor = new SecurityTokenDescriptor{Subject = new ClaimsIdentity(new[]{new Claim("Id", Guid.NewGuid().ToString()),new Claim(JwtRegisteredClaimNames.Sub, user.UserName),new Claim(JwtRegisteredClaimNames.Email, user.UserName),new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString())}),Expires = DateTime.UtcNow.AddMinutes(5),Issuer = issuer,Audience = audience,SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key),SecurityAlgorithms.HmacSha512Signature)};var tokenHandler = new JwtSecurityTokenHandler();var token = tokenHandler.CreateToken(tokenDescriptor);var jwtToken = tokenHandler.WriteToken(token);var stringToken = tokenHandler.WriteToken(token);return Results.Ok(stringToken);}return Results.Unauthorized();
});app.UseAuthentication();
app.UseAuthorization();app.Run();public class User
{public string UserName { get; set; }public string Password { get; set; }
}
调用示例
运行站点
用postman获取token
使用token访问目标链接