一、JWT结构

 JWT介绍就太多了,这里主要关注下Jwt的结构。 

 Jwt中包含三个部分:Header(头部).Payload(负载).Signature(签名)

  • Header:描述 JWT 的元数据的JSON对象,如:

    {"alg":"HS256","typ":"JWT"}
  • Payload:一个用来存放实际需要传递的数据的JSON 对象。如:

    "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": "admin",
    "exp": 1610877510,
    "iss": "cba",
    "aud": "cba"
    }
  • Signature:对前两部分(Header、Payload)的签名,防止数据篡改。
    HMACSHA256(base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)

  JWT示例:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiYWRtaW4iLCJleHAiOjE2MTA4Nzc1MTAsImlzcyI6ImNiYSIsImF1ZCI6ImNiYSJ9.O9lbZwfqRuA6vKcRCfYieA1zLkTPppdSvTc8UzwCkNw

二、ASP.NET Core 使用JTW认证

 1、添加Nuget包引用:

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

 2、定义一个JwtSettingDto结构,用于读取JWT配置信息

public class JwtSetting
{
/// <summary>
/// 发行者
/// </summary>
public string Issuer { get; set; }
/// <summary>
/// 受众
/// </summary>
public string Audience { get; set; }
/// <summary>
/// 秘钥
/// </summary>
public string SecretKey { get; set; }
/// <summary>
/// 过期时间
/// </summary>
public int AccessExpiration { get; set; }
/// <summary>
/// 刷新时间
/// </summary>
public int RefreshExpiration { get; set; }
}

 3、在appsetting.json配置文件中,添加jwt相关配置信息

  "JWTSetting": {
"Issuer": "cba",
"Audience": "cba",
"SecretKey": "123456789abcdefghi",
"AccessExpiration": 60,
"RefreshExpiration": 80
}

 4、在Startup.cs 中启用Jwt认证

public void ConfigureServices(IServiceCollection services)
{
services.Configure<JwtSetting>(Configuration.GetSection("JWTSetting"));
var token = Configuration.GetSection("JWTSetting").Get<JwtSetting>();
//JWT认证
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(token.SecretKey)),
ValidIssuer = token.Issuer,
ValidAudience = token.Audience,
ValidateIssuer = false,
ValidateAudience = false
};
});
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseAuthentication();
app.UseAuthorization();
}

 5、实现认证控制器:

  a) 添加认证Dto

public class LoginDto
{
[Required]
public string Username { get; set; } [Required]
public string Password { get; set; }
}

  b) 实现用户校验服务:默认实现:当用户密码都等于admin通过校验  

public interface IUserService
{
bool IsValid(LoginDto request);
} public class UserService : IUserService
{
//本次,固定校验admin
public bool IsValid(LoginDto request)
{
return request.Password == request.Username && request.Username == "admin";
}
}

  c) 实现签发token的认证服务:  

//认证服务接口
public interface IAuthenticateService
{
bool IsAuthenticated(LoginDto request, out string token);
} //认证服务
public class TokenAuthenticationService : IAuthenticateService
{
private readonly IUserService _userService;
private readonly JwtSetting _jwtSetting; public TokenAuthenticationService(IUserService userService, IOptions<JwtSetting> jwtSetting)
{
_userService = userService;
_jwtSetting = jwtSetting.Value;
} public bool IsAuthenticated(LoginDto request, out string token)
{
token = string.Empty;
if (!_userService.IsValid(request))
return false;
var claims = new[] { new Claim(ClaimTypes.Name, request.Username) };
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSetting.SecretKey));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var jwtToken = new JwtSecurityToken(_jwtSetting.Issuer, _jwtSetting.Audience, claims, expires: DateTime.Now.AddMinutes(_jwtSetting.AccessExpiration), signingCredentials: credentials);
token = new JwtSecurityTokenHandler().WriteToken(jwtToken);
return true;
}
}

  d) 添加认证控制器

[Route("api/[controller]")]
[ApiController]
public class AuthenticationController : ControllerBase
{
private IAuthenticateService _authService; public AuthenticationController(IAuthenticateService authService)
{
_authService = authService;
}
[AllowAnonymous]
[HttpPost, Route("RequestToken")]
public ActionResult RequestToken([FromBody] LoginDto request)
{
if (!ModelState.IsValid)
{
return BadRequest("Invalid Request");
}
string token;
if (_authService.IsAuthenticated(request, out token))
{
return Ok(token);
}
return BadRequest("Invalid Request");
}
}

 6、注入服务:TokenAuthenticationService 、UserService

services.AddScoped<IUserService, UserService>();
services.AddScoped<IAuthenticateService, TokenAuthenticationService>();

 7、添加测试控制器:

[Authorize]
[Route("api/[controller]")]
[ApiController]
public class AuditLogController : ControllerBase
{
// GET: api/<AuditLogController>
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}

    到此Jwt认证在.net core中已经实现,接下来验证下运行效果

三、验证结果

 1、请求AuditLog接口:api/AuditLog未传入认证信息时:

  

 2、获取Token:

  

 3、添加token调用接口:

  

四、Swagger UI添加认证

  在项目中通常都添加了Swagger UI来展示接口及基础测试,那么如果添加了认证后,如何在调用接口前添加认证信息呢?

  在Startup中:ConfigureServices中添加Swagger设置时,添加认证设置

//注册Swagger生成器,定义一个和多个Swagger 文档
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "AuditLogDemo API", Version = "v1" });
#region 启用swagger验证功能
//添加一个必须的全局安全信息,和AddSecurityDefinition方法指定的方案名称一致即可。
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] { }
}
});
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT授权(数据将在请求头中进行传输) 在下方输入Bearer {token} 即可,注意两者之间有空格",
Name = "Authorization",//jwt默认的参数名称
In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)
Type = SecuritySchemeType.ApiKey,
BearerFormat = "JWT",
Scheme = "Bearer", });
#endregion
});

  运行效果: 添加token->调用需认证接口

   

      

其他:

  源码地址:https://github.com/cwsheng/AuditLogDemo.git

ASP.NET Core - JWT认证实现的更多相关文章

  1. ASP.NET Core JWT认证授权介绍

    using JWTWebApi.Models; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetC ...

  2. asp.net core 自定义认证方式--请求头认证

    asp.net core 自定义认证方式--请求头认证 Intro 最近开始真正的实践了一些网关的东西,最近写几篇文章分享一下我的实践以及遇到的问题. 本文主要介绍网关后面的服务如何进行认证. 解决思 ...

  3. ASP.NET Core Token认证

    翻译:Token Authentication in ASP.NET Core 令牌认证(Token Authentication)已经成为单页应用(SPA)和移动应用事实上的标准.即使是传统的B/S ...

  4. 深入解读 ASP.NET Core 身份认证过程

    长话短说:上文我们讲了 ASP.NET Core 基于声明的访问控制到底是什么鬼? 今天我们乘胜追击:聊一聊ASP.NET Core 中的身份验证. 身份验证是确定用户身份的过程. 授权是确定用户是否 ...

  5. ASP.NET Core 身份认证 (Identity、Authentication)

    Authentication和Authorization 每每说到身份验证.认证的时候,总不免说提及一下这2个词.他们的看起来非常的相似,但实际上他们是不一样的. Authentication想要说明 ...

  6. CZGL.Auth: ASP.NET Core Jwt角色授权快速配置库

    CZGL.Auth CZGL.Auth 是一个基于 Jwt 实现的快速角色授权库,ASP.Net Core 的 Identity 默认的授权是 Cookie.而 Jwt 授权只提供了基础实现和接口,需 ...

  7. asp.net core 外部认证多站点模式实现

    PS:之前因为需要扩展了微信和QQ的认证,使得网站是可以使用QQ和微信直接登录.github 传送门 .然后有小伙伴问,能否让这个配置信息(appid, appsecret)按需改变,而不是在 Con ...

  8. 使用WebApi和Asp.Net Core Identity 认证 Blazor WebAssembly(Blazor客户端应用)

    原文:https://chrissainty.com/securing-your-blazor-apps-authentication-with-clientside-blazor-using-web ...

  9. asp.net core 身份认证/权限管理系统简介及简单案例

    如今的网站大多数都离不开账号注册及用户管理,而这些功能就是通常说的身份验证.这些常见功能微软都为我们做了封装,我们只要利用.net core提供的一些工具就可以很方便的搭建适用于大部分应用的权限管理系 ...

随机推荐

  1. Day5 - 06 函数的参数-命名关键字参数

    引子:对于关键字参数,调用时可以传入任意个不受限制的关键字参数,至于到底传入了哪些,就需要在函数内部通过[函数里定义的关键字参数]检查,例子里就是通过otherinfo检查.        >& ...

  2. celery定时执行任务 的使用

    1 参照博客 https://www.cnblogs.com/xiaonq/p/9303941.html#i1 1 创建celery_pro包   # 可在任意文件下 2 在 celery_pro 下 ...

  3. double类型和int类型的区别

    引例: double a=19*3.3; System.out.print(a); 结果为62.9999996,不是62.7:这里不单纯是因为给的是double类型 (1) 62.7 和 62.699 ...

  4. JAVA基础学习1

    一.JAVA是一种具有多种功能的高级语言:1,可以用于开发web页面上的小程序,桌面上运行的应用程序: 2,用于客户端服务器资源通讯的服务器端中间件: 3,还可以用于web服务器. 二.程序设计的5个 ...

  5. html 05-HTML标签图文详解(二)

    05-HTML标签图文详解(二) #本文主要内容 列表标签:<ul>.<ol>.<dl> 表格标签:<table> 框架标签及内嵌框架<ifram ...

  6. 移动端 rem和flexible

    一.rem布局 rem是相对于根元素的字体大小单位. 假设html的字体大小为16px,那么1rem = 16px; 一旦根元素html定义的font-size变化,整个页面中运用到的rem都会随之变 ...

  7. xss靶场练习(7.22)

    靶场地址:http://xss.fbisb.com/ 参考的文章:https://www.cnblogs.com/cute-puli/p/10834954.html  感谢大佬的分享 做这个题的思路就 ...

  8. Python 中更优雅的日志记录方案

    在 Python 中,一般情况下我们可能直接用自带的 logging 模块来记录日志,包括我之前的时候也是一样.在使用时我们需要配置一些 Handler.Formatter 来进行一些处理,比如把日志 ...

  9. Python将word文档转换成PDF文件

    如题. 代码: ''' #將word文档转换为pdf文件 #用到的库是pywin32 #思路上是调用了windows和office功能 ''' #导入所需库 from win32com.client ...

  10. 从零实现Linux一键自动化部署.netCore+Vue+Nginx项目到Docker中

    环境搭建 1.安装Linux,这里我用的阿里云服务器,CentOS7版本 2.进入Linux,安装Docker,执行以下命令 sudo yum update #更新一下yum包 sudo yum in ...