首先需要安裝的NuGet包有: Microsoft.AspNetCore.Authentication.JwtBearer Swashbuckle.AspNetCore Swashbuckle.AspNetCore.Filters jose-jwt 大致是這些代碼放到項目中如果有報錯信息再去具體解決 ...
首先需要安裝的NuGet包有:
Microsoft.AspNetCore.Authentication.JwtBearer
Swashbuckle.AspNetCore
Swashbuckle.AspNetCore.Filters
jose-jwt
大致是這些代碼放到項目中如果有報錯信息再去具體解決安裝需要的NuGet包。
首先需要在Startup.cs文件中的ConfigureServices方法中添加的代碼有
services.AddSwaggerGen(options =>
{
//開啟許可權鎖
options.OperationFilter<AddResponseHeadersFilter>();
options.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();
options.OperationFilter<SecurityRequirementsOperationFilter>();
//在header中添加token,傳遞到後臺
options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Description = "JWT授權(數據將在請求頭中進行傳遞)直接在下麵框中輸入Bearer {token}(註意兩者之間是一個空格) \"",
Name = "Authorization",//jwt預設的參數名稱
In = ParameterLocation.Header,//jwt預設存放Authorization信息的位置(請求頭中)
Type = SecuritySchemeType.ApiKey
});
});
//認證方案
services.AddAuthentication(option => {
option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(
option => {
option.TokenValidationParameters = new TokenValidationParameters
{
//是否驗證發行人
ValidateIssuer = true,
ValidIssuer = Configuration["JwtConfig:Issuer"],//發行人
//是否驗證受眾人
ValidateAudience = true,
ValidAudience = Configuration["JwtConfig:Audience"],//受眾人
//是否驗證密鑰
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtConfig:key"])),
ValidateLifetime = true, //驗證生命周期
RequireExpirationTime = true, //過期時間
ClockSkew = TimeSpan.Zero //平滑過期偏移時間
};
}
);
接著在Configure方法中開啟兩個中間件
//認證中間件
app.UseAuthentication();
//授權中間件
app.UseAuthorization();
然後在appsettings.json中加入以下配置
"JwtConfig": {
"key": "JWTStudyWebsite_DI20DXU3",
"Issuer": "testJwt",
"Audience": "wlw"
},
去使用一個簡單的登錄去測試JWT是否可以生成
/// <summary>
/// 登錄
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
public async Task<ResultDto> LoginAsync(LoginDto dto)
{
var uData = await _baseRepository.FindAsync(x => x.UserName == dto.UserName);
if (uData == null)
{
return new ResultDto
{
Result = Result.Failure,
Message = "未找到此用戶!"
};
}
else
{
if (uData.Password.ToUpper() == dto.Password.Md5().ToUpper())
{
var roleIds = _baseadminRoleResRepository.Queryable().Where(x => x.AdminId == uData.AdminId).Select(m=>m.RoleId).ToList();
//身份信息認證
//Session或Cookies換成JWT
IList<Claim> claims = new List<Claim> {
new Claim(JwtClaimTypes.Id,uData.AdminId.ToString()),
new Claim(JwtClaimTypes.Name,uData.UserName),
new Claim(ClaimTypes.Name,uData.UserName),
new Claim(ClaimTypes.Role,string.Join(',',roleIds))
};
//JWT密鑰
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtConfig:key"]));
//演算法
var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
//過期時間
DateTime expires = DateTime.UtcNow.AddMinutes(30);
//Payload負載
var token = new JwtSecurityToken(
issuer: configuration["JwtConfig:Issuer"],
audience: configuration["JwtConfig:Audience"],
claims: claims,
notBefore: DateTime.UtcNow,
expires: expires,
signingCredentials: cred
);
var handler = new JwtSecurityTokenHandler();
//生成令牌
string jwt = handler.WriteToken(token);
return new ResultDto
{
Result = Result.Success,
Message = "登錄成功",
Token = jwt,
};
}
else
{
return new ResultDto
{
Result = Result.Failure,
Message = "密碼錯誤!"
};
}
}
}
如果代碼中的有報錯的地方是需要引用一個NuGet包:IdentityModel
最後就可以生成Token了。