.net core 3.0webapi Jwt认证
程序员文章站
2024-01-21 19:01:40
...
.net core 3.0WebApi Jwt认证
1、在配置文件中appsettings.json加入Jwt配置信息
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"Authentication": {
"JwtBearer": {
"JwtOption": {
"TokenName": "token名称",
"Issuer": "签发人",
"Audience": "受众",
"Expires": "2", 过期时间
"SigningCredentials": "签名**"
}
}
}
}
2、创建相关类
public class JWTOption
{
/// <summary>
/// Token名称
/// </summary>
public string TokenName { get; set; }
/// <summary>
/// 签发人(一般写接口请求地址)
/// </summary>
public string Issuer{ get; set; }
/// <summary>
/// 受众(一般写接口请求地址)
/// </summary>
public string Audience { get; set; }
/// <summary>
/// 超时时间 单位小时
/// </summary>
public int Expires { get; set; }
/// <summary>
/// 哈希签名的秘钥 签名 Signing 证书 Credentials
/// </summary>
public string SigningCredentials { get; set; }
}
3、Startup.cs文件配置相关 验证
public void ConfigureServices(IServiceCollection services)
{
var jwtOption = new JWTOption();
Configuration.Bind("Authentication:JwtBearer:JwtOption", jwtOption);
services.AddSingleton<JWTOption>(jwtOption);
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
options.SaveToken = true;
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidIssuer = jwtOption.Issuer,
ValidAudience = jwtOption.Audience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOption.SigningCredentials))
};
options.Events = new JwtBearerEvents
{
OnTokenValidated = context =>
{
var userInfo = context.Principal.Claims.Where(a => a.Type == jwtOption.TokenName).FirstOrDefault();
if (userInfo == null) context.Fail("Unauthorized");
else
{
}
return Task.CompletedTask;
}
};
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseFileServer();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
4、创建token代码
[HttpGet("Login")]
[AllowAnonymous]
public IActionResult GetLogin()
{
var claims = new[] {new Claim(_jwtOption.TokenName,"我是一个JSON")};
var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtOption.SigningCredentials));
var token = new JwtSecurityToken(
issuer: _jwtOption.Issuer,
audience: _jwtOption.Audience,
expires: DateTime.Now.AddHours(_jwtOption.Expires),
claims: claims,
signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256));
return Ok(new
{
token = new JwtSecurityTokenHandler().WriteToken(token),
expiration = token.ValidTo,
});
}
上一篇: 那些年踩过的坑
推荐阅读
-
04 .NET CORE 2.2 使用OCELOT -- identity认证授权
-
.net core 3.0webapi Jwt认证
-
【.NET Core项目实战-统一认证平台】第四章 网关篇-数据库存储配置(2)
-
Asp.Net Core添加请求头自定义认证的示例
-
ASP.NET学习CORE中使用Cookie身份认证方法
-
asp.net core系列 60 Ocelot 构建服务认证示例
-
ASP.NET Core Authentication认证实现方法
-
Asp.Net Core基于JWT认证的数据接口网关实例代码
-
ASP.NET Core Identity 实战(3)认证过程
-
.net core webapi jwt 更为清爽的认证详解