一、注册身份验证服务
StartUp.ConfigureServices()
//身份验证 services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(setting.SecretKey)), ValidateAudience = true, ValidAudience = setting.Audience, ValidateIssuer = true, ValidIssuer = setting.Issuer, ClockSkew = TimeSpan.Zero, ValidateLifetime = true, RequireExpirationTime = true }; });
二、添加认证中间件(官方定义)
StartUp.Configure()
//这里注意 一定要在 UseMvc前面,顺序不可改变 app.UseAuthentication(); app.UseMvc();
三、设置Controller访问权限
将需要身份验证才可访问的 API 增加验证 [Authorize] ,如果允许匿名访问 ,添加 [AllowAnonymous]
[Route("api/[controller]")] [ApiController] [Authorize]//添加身份验证 ,所有Action都需要验证通过才可以访问 public class ValuesController : ControllerBase { // GET api/values [HttpGet] public ActionResult<IEnumerable<string>> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 [HttpGet("{id}")] [AllowAnonymous]//允许匿名访问 public ActionResult<string> Get(int id) { return "value"; } }
四、创建Token
[Route("api/[controller]")] [ApiController] public class TokenController : ControllerBase { JwtSettings setting;//Token 配置信息 //IOptions<JwtSettings> 是在 appsetting.json 的配置项,需要格外注意,SecretKey 必须>=16位 //需要提前在 StartUp.ConfigureServices注册 public TokenController(IOptions<JwtSettings> jwtSettings) { setting = jwtSettings.Value; } [HttpGet] public IActionResult Get() { try { var claims = new Claim[] { new Claim(ClaimTypes.Name, "ZhangSan"), new Claim(ClaimTypes.Role, "Admin,System"), };var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(setting.SecretKey)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( setting.Issuer, setting.Audience, claims, DateTime.Now, DateTime.Now.AddMinutes(30), creds); var result = new JwtSecurityTokenHandler().WriteToken(token); return Ok(result); } catch (Exception ex) { return BadRequest(ex.Message); } } }
五、测试
1、直接访问 /api/values,出现以下提示
2、访问 /api/values/1 可正常访问
3、请求 /api/token,然后添加到 /api/values 的 Headers 再次访问