新建一个空的asp.net core项目:
新建一个类Const放置一些常量:
public class Const
{
public const string SecurityKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDSfLGu+kcFDcJUCV46J+SbgR0lNc2NqgCGzojQTWW9xqjuzPF3mpisvTggYZSGfBzN+88YLZYbBLrDTUMJ4nTieElbP6SHkBFu8F+7fFBi7w3UPsaAXDr2E2srQYU5ZlKAcFBoNajNWj3sfSVRoYRPdqDTj4WdJlUPSNGz0wgRrQIDAQAB";
public const string Domain = "http://localhost:5000";
}
在Startup中向应用添加jwt验证服务:
//添加jwt验证:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => {
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,//是否验证Issuer
ValidateAudience = true,//是否验证Audience
ValidateLifetime = true,//是否验证失效时间
ClockSkew = TimeSpan.FromSeconds(30),
ValidateIssuerSigningKey = true,//是否验证SecurityKey
ValidAudience = Const.Domain,//Audience
ValidIssuer = Const.Domain,//Issuer,这两项和前面签发jwt的设置一致
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Const.SecurityKey))//拿到SecurityKey
};
});
管道中添加jwt验证:
//添加jwt验证
app.UseAuthentication();
由于管道有执行顺序的特性,因此最好放在管道的开始位置。
添加登录获取token的接口:
[ApiController]
[Route("[controller]")]
public class AuthController : ControllerBase
{
[AllowAnonymous]//指定此属性应用于的类或方法不需要授权。
[HttpGet]
public IActionResult Get(string userName, string pwd)
{
if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(pwd))
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
new Claim (JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddMinutes(30)).ToUnixTimeSeconds()}"),
new Claim(ClaimTypes.Name, userName)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Const.SecurityKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: Const.Domain,
audience: Const.Domain,
claims: claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
return Ok(new
{
token = new JwtSecurityTokenHandler().WriteToken(token)
});
}
else
{
return BadRequest(new { message = "username or password is incorrect." });
}
}
}
方法中对用户名和密码的验证只是简单的验空,实际应用中会更复杂,也会与数据库中的数据比对。
接下来就是对jwt的应用了。
新建HomeController,用于验证jwt是否成功启用:
[ApiController]
[Route("[controller]")]
public class HomeController : ControllerBase
{
[HttpGet]
[Route("api/value1")]
public ActionResult<IEnumerable> Get()
{
return new string[] { "value1", "value1" };
}
[HttpGet]
[Route("api/value2")]
[Authorize]
public ActionResult<IEnumerable> Get2()
{
return new string[] { "value2", "value2" };
}
}
其中Get()方法不需要验证,Get2()需要验证。
测试:
先测试Get()方法(接口名称时api/value1),因为此方法不用验证:
验证成功!!!
接下来测试Get2():
访问Get2()方法的接口名api/value2,粘贴上面获得的token到header中:
验证成功!!!
总结:至此,使用asp.net core 自带的jwt方法就完成了。
源码地址:
https://gitee.com/jingboweilanGO/Demo_jwt_core.git
说明:Demo-jwt-core是本篇文章涉及到的源码,是使用asp.net core 自带的jwt方法;
#红红火火过大年# 春节即将来临了,后天准备回老家了。可能不会及时的更新文章了。谢谢大家支持。