参照下面的博客一点问题没有
.Net Core使用JWT进行身份认证 - 汤姆茂 - 博客园
我自己在测试的时候 生成jwt的token报错:PII is hidden. For more details 参照下面的博客知道了原因是由于设置的key过短
asp.net core webapi 添加jwt生成token时报错_gnsyhxg的博客-CSDN博客
我把代码贴一下,此处集成了swagger,在.net5.0以及之后的版本自己集成swagger了,这里是.net core3.1版本
public class Secu
{
public static string SecurityKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDI2a2EJ7m872v0afyoSDJT2o1+SitIeJSWtLJU8/Wz2m7gStexajkeD+Lka6DSTy8gt9UwfgVQo6uKjVLG5Ex7PiGOODVqAEghBuS7JzIYU5RvI543nNDAPfnJsas96mSA7L/mD7RTE2drj6hf3oZjJpMPZUQI/B1Qjb5H3K3PNwIDAQAC";
public static string Developer = "felix";
}
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System;
using System.Text;
namespace WebApiT
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
//添加jwt验证:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => {
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,//是否验证Issuer
ValidateAudience = true,//是否验证Audience
ValidateLifetime = true,//是否验证失效时间
ClockSkew = TimeSpan.FromSeconds(30),
ValidateIssuerSigningKey = true,//是否验证SecurityKey
ValidAudience = Secu.Developer,//Audience
ValidIssuer = Secu.Developer,//Issuer,这两项和前面签发jwt的设置一致
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Secu.SecurityKey))//拿到SecurityKey
};
});
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("V1.0", new Microsoft.OpenApi.Models.OpenApiInfo
{
Title = "Felix.API",
Version = "V1.0",
Description = "ASP.NET CORE Felix.API",
Contact = new Microsoft.OpenApi.Models.OpenApiContact
{
Name = "Felix",
Email = ""
}
});
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token}(注意两者之间是一个空格)\"",
Name = "Authorization",//jwt默认的参数名称
In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)
Type = SecuritySchemeType.ApiKey
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement {
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference()
{Id = "Bearer",Type = ReferenceType.SecurityScheme}
},
Array.Empty<string>()
}
});
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
//启用Swagger中间件
app.UseSwagger();
//配置SwaggerUI
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/V1.0/swagger.json", "Felix.API");
});
}
}
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace WebApiT.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class LoginController : ControllerBase
{
//登录 获取token
[Route("Login"), HttpGet]
public IActionResult Login(string name, string password)
{
if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(password))
{
var claims = new[] {
new Claim(System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
new Claim (System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddMinutes(30)).ToUnixTimeSeconds()}"),
new Claim(ClaimTypes.Name, name)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Secu.SecurityKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: Secu.Developer,
audience: Secu.Developer,
claims: claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
return Ok(new
{
token = new JwtSecurityTokenHandler().WriteToken(token)
});
}
else
{
return BadRequest(new { message = "username or password is incorrect." });
}
}
}
}
然后在要需要授权的接口上添加[Authorize]即可
则该接口在收到请求时会先校验header中的Authorization
若将[Authorize]放到Controller上,则该Controller中的所有接口都需要校验header中的Authorization