.Net Core简单实用jwt进行token验证
-
安装NuGet包:
IdentityModel 4.2.0
Microsoft.AspNetCore.Authentication.JwtBearer 2.1.1
Microsoft.AspNetCore.Authorization 2.1.1 -
新建一个Models文件夹,在文件夹下建一个JwtSettings.cs类
public class JwtSettings
{
/// <summary>
/// token是谁颁发的
/// </summary>
public string Issuer { get; set; }
/// <summary>
/// token可以给那些客户端使用
/// </summary>
public string Audience { get; set; }
/// <summary>
/// 加密的key(SecretKey必须大于16个,是大于,不是大于等于)
/// </summary>
public string SecretKey { get; set; }
}
- 然后在appsettings.json中配置jwt参数的值 【注意】 SecretKey必须大于16个,是大于,不是大于等于
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"JwtSettings": {
"Issuer": "https://localhost:44336",
"Audience": "https://localhost:44336",
"SecretKey": "Hello-key----------"
}
}
- 在Startup.cs里面注入服务
- 在ConfigureServices方法下加入
#region Jwt配置
//将appsettings.json中的JwtSettings部分文件读取到JwtSettings中,这是给其他地方用的
services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings"));
//由于初始化的时候我们就需要用,所以使用Bind的方式读取配置
//将配置绑定到JwtSettings实例中
var jwtSettings = new JwtSettings();
Configuration.Bind("JwtSettings", jwtSettings);
//添加身份验证
services.AddAuthentication(options =>
{
//认证middleware配置
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(o =>
{
//jwt token参数设置
o.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = JwtClaimTypes.Name,
RoleClaimType = JwtClaimTypes.Role,
//Token颁发机构
ValidIssuer = jwtSettings.Issuer,
//颁发给谁
ValidAudience = jwtSettings.Audience,
//这里的key要进行加密
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey)),
/***********************************TokenValidationParameters的参数默认值***********************************/
// RequireSignedTokens = true,
// SaveSigninToken = false,
// ValidateActor = false,
// 将下面两个参数设置为false,可以不验证Issuer和Audience,但是不建议这样做。
// ValidateAudience = true,
// ValidateIssuer = true,
// ValidateIssuerSigningKey = false,
// 是否要求Token的Claims中必须包含Expires
// RequireExpirationTime = true,
// 允许的服务器时间偏移量
// ClockSkew = TimeSpan.FromSeconds(300),
// 是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比
// ValidateLifetime = true
};
});
#endregion
- 在Configure方法下加入
#region 身份验证
app.UseAuthentication();
#endregion
- 新增一个实体类app_mobile_user
public class app_mobile_user
{
public long id { get; set; }
/// <summary>
/// 手机号
/// </summary>
public string phone { get; set; }
/// <summary>
/// 密码
/// </summary>
public string password { get; set; }
}
- 接下来在Controllers文件夹下新建控制器userController.cs,完整代码如下
namespace Mms.Api.Controllers
{
[Route("[controller]")]
[ApiController]
public class userController : ControllerBase
{
//获取JwtSettings对象信息
private JwtSettings _jwtSettings;
public userController(IOptions<JwtSettings> _jwtSettingsAccesser)
{
_jwtSettings = _jwtSettingsAccesser.Value;
}
/// <summary>
/// 获取token
/// </summary>
/// <param name="user"></param>
private object Token(app_mobile_user model)
{
//测试自己创建的对象
var user = new app_mobile_user
{
id = 1,
phone = "138000000",
password = "e10adc3949ba59abbe56e057f20f883e"
};
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.UTF8.GetBytes(_jwtSettings.SecretKey);
var authTime = DateTime.Now;//授权时间
var expiresAt = authTime.AddDays(30);//过期时间
var tokenDescripor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[] {
new Claim(JwtClaimTypes.Audience,_jwtSettings.Audience),
new Claim(JwtClaimTypes.Issuer,_jwtSettings.Issuer),
new Claim(JwtClaimTypes.Name, user.phone.ToString()),
new Claim(JwtClaimTypes.Id, user.id.ToString()),
new Claim(JwtClaimTypes.PhoneNumber, user.phone.ToString())
}),
Expires = expiresAt,
//对称秘钥SymmetricSecurityKey
//签名证书(秘钥,加密算法)SecurityAlgorithms
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescripor);
var tokenString = tokenHandler.WriteToken(token);
var result = new
{
access_token = tokenString,
token_type = "Bearer",
profile = new
{
id = user.id,
name = user.phone,
phone = user.phone,
auth_time = authTime,
expires_at = expiresAt
}
};
return result;
}
[Route("get_token")]
[HttpPost]
public IActionResult GetToken()
{
return Ok(Token(null));
}
[Authorize]
[Route("get_user_info")]
[HttpPost]
public IActionResult GetUserInfo()
{
//获取当前请求用户的信息,包含token信息
var user = HttpContext.User;
return Ok();
}
}
- 接下来就开始做验证!PostMan测试获取token
- 这样可以成功获取token,下面来做权限校验在需要授权的api上新增 [Authorize] 标记
- 携带token访问,返回了想要的数据
来源文章:https://www.cnblogs.com/pingming/p/11169799.html