Swagger与JWT
Swagger与JWT
创建项目后首先我们要引用这几个包
打开appsettings.json在里面添加
"LemonToken": { "secret":"123456789123456789", "issuer": "text.cn",//发行人 "audience": "test",//订阅人 "accessExpiraction": 180000,//过期时间 "refreshExpiration": 60//刷新时间 秒 },
创建个文件夹tokens在里面创建个LemonToken类
public class LemonToken { [JsonProperty("Secret")] public string Secret { get; set; } [JsonProperty("Issuer")] public string Issuer { get; set; } [JsonProperty("Audience")] public string Audience { get; set; } [JsonProperty("AccessExpiration")] public int AccessExpiration { get; set; } [JsonProperty("RefreshExpiration")] public string RefreshExpiration { get; set; } }
在右键项目属性,点击生成。找到XML文档文件并打勾,在取消显示警告(S):里面加上1591
在点击Startup,找到 public void ConfigureServices(IServiceCollection services)并在里面加上
var basePath = Microsoft.DotNet.PlatformAbstractions.ApplicationEnvironment.ApplicationBasePath; services.AddSwaggerGen(a => { a.SwaggerDoc("a", new OpenApiInfo { Version = "a", Title = "第一个接口标题", Description = $"Description的描述", Contact = new OpenApiContact { Name = "zhangsan", Email = "1919675978@qq.com", Url = new Uri("https://www.cnblogs.com/mvpbest/") }, License = new OpenApiLicense { Name = "lisi", Url = new Uri("https://www.cnblogs.com/mvpbest/") } }); a.OrderActionsBy(a => a.RelativePath); var Xmalpath = Path.Combine(basePath, "JWTExercise.xml"); a.IncludeXmlComments(Xmalpath, true); //SecurityDefinition安全定义 //公开的接口安全方案 a.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme() { Description = "在下框中输入请求头中需要添加Jwt授权Token:Bearer Token", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, BearerFormat = "JWTExercise", Scheme = "Bearer" }); a.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme{ Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer"} },new string[] { } } }); }); LemonToken lemonToken = Configuration.GetSection("LemonToken").Get<LemonToken>(); services.AddAuthentication("Bearer") .AddJwtBearer(option => { option.TokenValidationParameters = new TokenValidationParameters() { ValidateIssuerSigningKey = true, ValidateIssuer = true, ValidIssuer = lemonToken.Issuer, ValidateAudience = true, ValidAudience = lemonToken.Audience, ValidateLifetime = true, ClockSkew = new TimeSpan(30), RequireExpirationTime = true, SaveSigninToken = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(lemonToken.Secret)) }; }); services.AddAuthorization(options => { //单独角色 options.AddPolicy("Client", policy => policy.RequireRole("Client").Build()); //或的关系 options.AddPolicy("SystemOrAdmin", policy => policy.RequireRole("Admin", "System").Build()); //与的关系 options.AddPolicy("SystemAndAdmin", policy => policy.RequireRole("System").RequireRole("Admin")); });
在找到Configure按下面写,记得位置不能弄错
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint($"swagger/a/swagger.json", $"a");// 将swagger设置成首页 //访问该文件,注意localhost:8001/swagger是访问不到的, //去launchSettings.json把launchUrl去掉 c.RoutePrefix = ""; }); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
找到launchSettings.json按一下改
{ "$schema": "http://json.schemastore.org/launchsettings.json", "profiles": { "JWTExercise": { "commandName": "Project", "launchBrowser": true, "launchUrl": "", "applicationUrl": "http://localhost:5000", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } }
在创建一个Home控制器
[Route("api/[controller]/[action]")] [ApiController] public class HomeController : ControllerBase { private readonly ILogger<HomeController> _logger; private readonly IConfiguration _configuration; public HomeController(IConfiguration configuration, ILogger<HomeController> logger) { _logger = logger; _configuration = configuration; } #region 获取token /// <summary> /// token获取接口数据 /// </summary> [HttpGet] public string Gettoken() { LemonToken lemon = _configuration.GetSection("LemonToken").Get<LemonToken>(); Claim[] claim = { new Claim(JwtRegisteredClaimNames.FamilyName,"猴三棍"), new Claim(JwtRegisteredClaimNames.Sub,"屁股朝天"), new Claim(JwtRegisteredClaimNames.Email,"120@qq.com"), new Claim(ClaimTypes.Role,"Client") }; JwtSecurityToken token = new JwtSecurityToken( issuer: lemon.Issuer, audience: lemon.Audience, claims: claim, expires: DateTime.Now.AddMinutes(lemon.AccessExpiration), signingCredentials: new SigningCredentials( new SymmetricSecurityKey(Encoding.ASCII.GetBytes(lemon.Secret)) , SecurityAlgorithms.HmacSha256) ); string JwtToken = new JwtSecurityTokenHandler().WriteToken(token); return JwtToken; } #endregion [HttpGet] [Authorize] public string Find() { return "成功"; } }
点击执行
直接点击无法显示输出的值
而你先点击下面的获取到了密钥,在登陆就可以有权限了