.netcore3.1添加swagger及JWT Authorize 验证
上一篇我们已经弄好了swaager ,接下赖集成一下jwt进行认证。
首先引入Microsoft.AspNetCore.Authentication.JwtBearer nuget包
在startup中加入jwt配置。这里ValidIssuer和ValidAudience和secret 最好配置一下,我这里写死了。
services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("123456111111111111111111")),//token.Secret)), ValidIssuer = "webapi.cn",//token.Issuer, ValidAudience = "WebApi",//token.Audience, ValidateIssuer = true, ValidateAudience = true }; }); }
在上一篇swagger的配置中加入jwt验证配置
services.AddSwaggerGen(s => { s.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); s.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme() { Description = "在下框中输入请求头中需要添加Jwt授权Token:Bearer Token", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, BearerFormat = "JWT", Scheme = "Bearer" }); s.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme{ Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer"} },new string[] { } } }); });
这样swaager的jwt授权认证就弄好了,接下来写个接口获取一下token
[HttpGet] [Route("/GetToken")] public ActionResult<string> GetToken() { var claims = new[] { new Claim(ClaimTypes.Name,"Ers") }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("123456111111111111111111")); var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var jwtToken = new JwtSecurityToken("webapi.cn", "WebApi", claims, expires: DateTime.Now.AddMinutes(30), signingCredentials: credentials); var token = new JwtSecurityTokenHandler().WriteToken(jwtToken); return token; }
在原来的天气接口上加上[Authorize] 特性
在startup管道中启用授权app.UseAuthentication();
运行一下,访问天气接口,发现访问不了,因为加了[Authorize]特性后需要认证,如下图,出现401没有权限的标志。
访问swagger主页出现一个Authorize的标志,点击可以输入jwt的验证字符。
运行获取weatherforecast接口,运行结果还是401,因为我们在接口添加了【Authorize】后接口需要一个认证
现在去拿一下token,运行GetToken,获取Token字符串,
将字符串添加到swagger提供的Authorize认证框里面,粘贴token之前要写上Bearer加一个空格,再粘上token.点击Authorize,完成。
再次运行获取天气接口
成功了,。