.net core Jwt 添加

Jwt 已经成为跨平台身份验证通用方案,如不了解请关注:https://jwt.io/。

为了和微软其他验证模块有个比较好的衔接,项目中采用了微软开发的jwt组件: System.IdentityModel.Tokens.Jwt。首先安装:Install-Package System.IdentityModel.Tokens.Jwt

   在config方法中添加

  if (!HostingEnvironment.IsEnvironment("test"))
{
app.UseJwtBearerAuthentication(Jwt.GetJwtOptions());
}

实现一个jwt工具类:

 using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using NDaisy.Core.ServiceLocator;
using WebApiCore.Core.Utility.Extension;
using IHostingEnvironment = Microsoft.AspNetCore.Hosting.IHostingEnvironment; namespace WebApiCore.Utility
{
public class Jwt
{
private static SecurityKey _signKey;
private static IConfigurationSection _config;
private const string Issue = "webcore";
static Jwt()
{
_config= ServiceLocator.Current.GetInstance<IConfigurationRoot>().GetSection("Jwt");
var keyAsBytes = Encoding.ASCII.GetBytes(_config.GetValue<string>("Salt"));
_signKey = new SymmetricSecurityKey(keyAsBytes); } public static JwtBearerOptions GetJwtOptions()
{
return new JwtBearerOptions
{
TokenValidationParameters =
{
ValidIssuer = Issue,
IssuerSigningKey = _signKey,
ValidateLifetime = true,
ValidateIssuer = true,
ValidateAudience = false
},
Events = new JwtBearerEvents()
{
OnAuthenticationFailed = c =>
{ return Task.Run(() =>
{
if (ServiceLocator.Current.GetInstance<IHostingEnvironment>().IsDevelopment())
{
c.Request.GetDisplayUrl().LogInfo();
c.Exception.LogError();
} } );
} }
};
} public static string SignToken(IList<Claim> claims)
{
var seconds= _config.GetValue<int>("SlideTime"); JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(issuer: Issue, claims: claims, expires: DateTime.UtcNow.AddSeconds(seconds), signingCredentials: new SigningCredentials(_signKey, SecurityAlgorithms.HmacSha256)); return new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
}
} }

添加一个获取token的入口,实际项目中,放在登录授权里面:

  app.Map("/auth/test", appbuilder =>
{
appbuilder.Run(d =>
{
var token= Jwt.SignToken(new List<Claim>() {new Claim("name", "ryan")}); return d.Response.WriteAsync(token);
});
});
上一篇:Laravel-lumen 配置JWT


下一篇:用JWT来保护我们的ASP.NET Core Web API