.net core的使用JWT身份認證模式
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, "
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 Swagger
services.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 = Path.Combine(basePath, "TestCore.xml");
//var xmlPath = "/opt/zili/gongyeyun/TestCore.xml";
options.IncludeXmlComments(xmlPath);
});