摘要
本文演示如何向无效用户提供jwt,以及如何在webapi中应用该token通过JwtBearerMiddleware中间件对用户进行身份认证。
认证和受权区别?
首先咱们要弄清楚认证(Authentication)和受权(Authorization)的区别,免得混同了。认证是确认的过程中你是谁,而受权围绕是你被容许做什么,即权限。显然,在确认容许用户做什么之前,你须要晓得他们是谁,因而,在须要受权时,还必须以某种形式对用户进行身份验证。
什么是JWT?
依据维基百科的定义,JSON WEB Token(JWT),是一种基于JSON的、用于在网络上申明某种主张的令牌(token)。JWT通常由三局部组成:头信息(header),音讯体(payload)和签名(signature)。
头信息指定了该JWT应用的签名算法:
header = '{"alg":"HS256","typ":"JWT"}'
HS256
示意应用了HMAC-SHA256来生成签名。
音讯体蕴含了JWT的用意:
payload = '{"loggedInAs":"admin","iat":1422779638}'//iat示意令牌生成的工夫
未签名的令牌由base64url
编码的头信息和音讯体拼接而成(应用"."分隔),签名则通过公有的key计算而成:
key = 'secretkey' unsignedToken = encodeBase64(header) + '.' + encodeBase64(payload) signature = HMAC-SHA256(key, unsignedToken)
最初在未签名的令牌尾部拼接上base64url
编码的签名(同样应用"."分隔)就是JWT了:
token = encodeBase64(header) + '.' + encodeBase64(payload) + '.' + encodeBase64(signature)# token看起来像这样: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dnZWRJbkFzIjoiYWRtaW4iLCJpYXQiOjE0MjI3Nzk2Mzh9.gzSraSYS8EXBxLN_oWnFSRgCzcmJmMjLiuyu5CSpyHI
JWT经常被用作爱护服务端的资源(resource),客户端通常将JWT通过HTTP的Authorization
header发送给服务端,服务端应用本人保留的key计算、验证签名以判断该JWT是否可信:
Authorization: Bearer eyJhbGci*...<snip>...*yu5CSpyHI
筹备工作
应用vs2019创立webapi我的项目,并且装置nuget包
Microsoft.AspNetCore.Authentication.JwtBearer
Startup类
ConfigureServices 增加认证服务
services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { options.SaveToken = true; options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters() { ValidateIssuer = true, ValidateAudience = true, ValidAudience = "https://xx", ValidIssuer = "https://xx", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SecureKeySecureKeySecureKeySecureKeySecureKeySecureKey")) }; });
Configure 配置认证中间件
app.UseAuthentication();//认证中间件
创立一个token
增加一个登录model命名为LoginInput
public class LoginInput { public string Username { get; set; } public string Password { get; set; } }
增加一个认证控制器命名为AuthenticateController
[Route("api/[controller]")] public class AuthenticateController : Controller { [HttpPost] [Route("login")] public IActionResult Login([FromBody]LoginInput input) { //从数据库验证用户名,明码 //验证通过 否则 返回Unauthorized //创立claim var authClaims = new[] { new Claim(JwtRegisteredClaimNames.Sub,input.Username), new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString()) }; IdentityModelEventSource.ShowPII = true; //签名秘钥 能够放到json文件中 var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SecureKeySecureKeySecureKeySecureKeySecureKeySecureKey")); var token = new JwtSecurityToken( issuer: "https://xx", audience: "https://xx", expires: DateTime.Now.AddHours(2), claims: authClaims, signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256) ); //返回token和过期工夫 return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo }); } }
增加api资源
利用默认的控制器WeatherForecastController
- 增加个Authorize标签
- 路由调整为:[Route("api/[controller]")] 代码如下
[Authorize] [ApiController] [Route("api/[controller]")] public class WeatherForecastController : ControllerBase
到此所有的代码都曾经准好了,上面进行运行测试
运行我的项目
应用postman进行模仿
- 发现返回时401未认证,上面获取token
- 通过用户和明码获取token
- 如果咱们的凭证正确,将会返回一个token和过期日期,而后利用该令牌进行拜访
- 利用token进行申请
- 现申请状态200!
原文:[https://www.cnblogs.com/cheng...]()