上一篇轉載的文章中解釋了jwt的種種,.net core中使用jwt的方式
使用.net core內置方式實現jwt
使用JwtSecurityTokenHandler實現生成jwt
生成 token
這里我隨便定義了一個secret叫mysecret12345678,認證的時候也要用到這個。
public static string GetJwtAccessToken(ClaimsIdentity claimsIdentity)
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes("mysecret12345678");
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = claimsIdentity,
Expires = DateTime.UtcNow.AddHours(10),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
注入認證
/// <summary>
/// 注冊JWT Bearer認證服務的靜態擴展方法
/// </summary>
/// <param name="services"></param>
/// <param name="appSettings">JWT授權的配置項</param>
public static void AddJwtBearerAuthentication(this IServiceCollection services)
{
//使用應用密鑰得到一個加密密鑰字節數組
var key = Encoding.ASCII.GetBytes("mysecret12345678");
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddCookie(cfg => cfg.SlidingExpiration = true)
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = true;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
}
services.AddJwtBearerAuthentication();
添加認證
注入認證及添加認證后,凡是添加Authorize特性的接口都如使用注入的策略進行認證。
app.UseAuthentication();
接口使用認證
添加兩個接口,一個生成token,另一個加上Authorize特性使用認證。如果直接訪問testtoken接口會報401,用GetToken接口生成的token去請求testtoken接口執行正常。說明token認證已經生效了。一個最簡單的示例完成了。
[HttpGet]
public string GetToken()
{
var token = JwtBearerAuthenticationExtension.GetJwtAccessToken(new ClaimsIdentity(
new Claim[]{
new Claim("userId","1"),
new Claim("userName","2"),
new Claim("userAccount","3")
})
);
return token;
}
[HttpGet("testtoken")]
[Authorize]
public string TestToken()
{
return "1";
}
內置方式生成jwt token的困惑
內置方式生成jwt很簡單,從生成到認證,簡單一些代碼即可完成。但是,我想要刷新token呢,抱歉,要自己去實現。我想要在幾個微服務中使用一套呢,抱歉,也比較麻煩。有沒有其他方式簡單解決呢,有!就是我們接下來講的IdentityServer4。
使用IdentityServer4內置方式實現jwt
IdentityServer4 是為ASP.NET Core 2.系列量身打造的一款基於 OpenID Connect 和 OAuth 2.0 認證框架。具體的可以查看http://www.identityserver.com.cn/
后續我會寫一系列IdentityServer4實戰來實踐統一認證和token刷新。