1.使用JWT身份认证模式,引入库:IdentityServer4.AccessTokenValidation
2.在StartUp.cs中添加加密秘钥串:
public static readonly SymmetricSecurityKey symmetricKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("need_to_get_this_from_enviroment"));
3.在ConfigureServices方法中在services.AddMvc();之前添加代码:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>{o.TokenValidationParameters = new TokenValidationParameters{NameClaimType = JwtClaimTypes.Name,RoleClaimType = JwtClaimTypes.Role,ValidIssuer = "YFAPICommomCore",ValidAudience = "api",IssuerSigningKey = symmetricKey/***********************************TokenValidationParameters的参数默认值***********************************/// RequireSignedTokens = true,// SaveSigninToken = false,// ValidateActor = false,// 将下面两个参数设置为false,可以不验证Issuer和Audience,但是不建议这样做。// ValidateAudience = true,// ValidateIssuer = true, // ValidateIssuerSigningKey = false,// 是否要求Token的Claims中必须包含Expires// RequireExpirationTime = true,// 允许的服务器时间偏移量// ClockSkew = TimeSpan.FromSeconds(300),// 是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比// ValidateLifetime = true};});
在Configure方法中app.UseMvc();之前添加代码:
app.UseAuthentication();
4.在一个ApiController中增加生成access_token的方法:
[HttpPost("authenticate")]public IActionResult Authenticate([FromBody]User userDto){var tokenHandler = new JwtSecurityTokenHandler();var authTime = DateTime.UtcNow;var expiresAt = authTime.AddDays(7);var tokenDescriptor = new SecurityTokenDescriptor{Subject = new ClaimsIdentity(new Claim[]{new Claim(JwtClaimTypes.Audience,"api"),new Claim(JwtClaimTypes.Issuer,"YFAPICommomCore"),new Claim(JwtClaimTypes.Id, "1"),new Claim(JwtClaimTypes.Name, "xxx"),new Claim(JwtClaimTypes.Email, "xxx@"),new Claim(JwtClaimTypes.PhoneNumber, "13500000000")}),Expires = expiresAt,SigningCredentials = new SigningCredentials(Startup.symmetricKey, SecurityAlgorithms.HmacSha256Signature)};var token = tokenHandler.CreateToken(tokenDescriptor);var tokenString = tokenHandler.WriteToken(token);return Ok(new{access_token = tokenString,token_type = "Bearer",profile = new{sid = "1",name = "xxxx",auth_time = new DateTimeOffset(authTime).ToUnixTimeSeconds(),expires_at = new DateTimeOffset(expiresAt).ToUnixTimeSeconds()}});}
5.然后就可以在任意ApiController方法中添加 [Authorize] 使用了:
[Authorize][HttpPost][HttpGet]public string Test2(){var identity = (ClaimsIdentity)User.Identity;var id = identity.Claims.FirstOrDefault(u=>u.Type== JwtClaimTypes.Id).Value;return "test auth";}
注意:在ConfigureServices中初始化Swagger的时候,可以加上对auth的支持。
Init Swaggerservices.AddSwaggerGen(options =>{options.SwaggerDoc("v1", new Info{Version = "v1",Title = "WebAPI"});//启用auth支持options.AddSecurityDefinition("Bearer", new ApiKeyScheme{Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",Name = "Authorization",In = "header",Type = "apiKey"});///Determine base path for the application. var basePath = PlatformServices.Default.Application.ApplicationBasePath;var xmlPath = bine(basePath, "TestCore.xml");//var xmlPath = "/opt/zili/gongyeyun/TestCore.xml";options.IncludeXmlComments(xmlPath);});
工程git地址:/zzzili/YFAPICommonCore