Asp .net core JWT验证
2021/9/6 1:36:58
本文主要是介绍Asp .net core JWT验证,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
Jwt
安装Nuget包 3 1IdentityModel 版本3.10.102
Microsoft.AspNetCore.Authorization 版本2.2.03
Microsoft.AspNetCore.Authentication.JwtBearer 版本2.2.0类 17 1
public class JwtSettings2
{3
/// <summary>4
/// token是谁颁发的5
/// </summary>6
public string Issuer { get; set; }7 8
/// <summary>9
/// token可以给那些客户端使用10
/// </summary>11
public string Audience { get; set; }12 13
/// <summary>14
/// 加密的key(SecretKey必须大于16个,是大于,不是大于等于)15
/// </summary>16
public string SecretKey { get; set; }17
}appsetting配置添加 6 1
,2
"JwtSettings": {3
"Issuer": "https://localhost:44336",//谁颁发的4
"Audience": "https://localhost:44336",//允许谁使用5
"SecretKey": "Hello-key----------"//加密密钥大于166
}startup注入服务 57 1
ConfigureServices()里面添加2
/*注入Jwt服务*/3 4
//将appsettings.json中的JwtSettings部分文件读取到JwtSettings中,这是给其他地方用的5
services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings"));6
var jwtsettings = new JwtSettings();7
//将配置绑定到JwtSettings实例中8
Configuration.Bind("JwtSettings", jwtsettings);9
//添加身份验证10
services.AddAuthentication(options=> {11
//认证middleware配置12
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;13
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;14
}).15
AddJwtBearer(o =>16
{17
//jwt token参数设置18
o.TokenValidationParameters = new TokenValidationParameters19
{20
NameClaimType = JwtClaimTypes.Name,21
RoleClaimType = JwtClaimTypes.Role,22
//Token颁发机构23
ValidIssuer = jwtsettings.Issuer,24
//颁发给谁25
ValidAudience = jwtsettings.Audience,26
//这里的key要进行加密27
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtsettings.SecretKey)),28 29
/***********************************TokenValidationParameters的参数默认值***********************************/30
// RequireSignedTokens = true,31
// SaveSigninToken = false,32
// ValidateActor = false,33
// 将下面两个参数设置为false,可以不验证Issuer和Audience,但是不建议这样做。34
// ValidateAudience = true,35
// ValidateIssuer = true,36
// ValidateIssuerSigningKey = false,37
// 是否要求Token的Claims中必须包含Expires38
// RequireExpirationTime = true,39
// 允许的服务器时间偏移量40
// ClockSkew = TimeSpan.FromSeconds(300),41
// 是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比42
// ValidateLifetime = true43
};44
});45
/*声明授权*/46
services.AddAuthorization(options =>47
{48
options.AddPolicy("IsUser", policy => policy.RequireClaim("IsAdmin", "false"));49
options.AddPolicy("IsAdmin", policy => policy.RequireClaim("IsAdmin", "true"));50
/*角色*/51
//options.AddPolicy("IsAdmin", policy => policy.RequireRole("Administrator", "admin","member"));52
});53 54
configure()里面添加55
//身份授权认证56
app.UseAuthentication();57
app.UseHttpsRedirection();依赖注入,要验证的地方添加[Authorize],运行未验证的用户访问[AllowAnonymous] 100 1
namespace Jwt.Controllers2
{3
[ApiController]4
[Route("[controller]")]5
public class WeatherForecastController : ControllerBase6
{7 8
//获取JwtSettings对象信息9
private JwtSettings _jwtSettings;10
public WeatherForecastController(IOptions<JwtSettings> _jwtSettingsAccesser)11
{12
_jwtSettings = _jwtSettingsAccesser.Value;13
}14 15
/// <summary>16
/// 获取token17
/// </summary>18
/// <param name="user"></param>19
private object Token(user model)20
{21
//测试自己创建的对象22
var user = new user23
{24
id = 1,25
username = "138000000",26
password = "e10adc3949ba59abbe56e057f20f883e"27
};28
var tokenHandler = new JwtSecurityTokenHandler();29 30
var key = Encoding.UTF8.GetBytes(_jwtSettings.SecretKey);31
var authTime = DateTime.Now;//授权时间32
var expiresAt = authTime.AddDays(0.1);//过期时间33
var tokenDescripor = new SecurityTokenDescriptor34
{35
Subject = new ClaimsIdentity(new Claim[] {36
new Claim(JwtClaimTypes.Audience,_jwtSettings.Audience),37
new Claim(JwtClaimTypes.Issuer,_jwtSettings.Issuer),38
new Claim(JwtClaimTypes.Name, user.username.ToString()),39
new Claim("IsMember", member), //声明授权40
}),41
Expires = expiresAt,42
//对称秘钥SymmetricSecurityKey43
//签名证书(秘钥,加密算法)SecurityAlgorithms44
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)45
};46
var token = tokenHandler.CreateToken(tokenDescripor);47
var tokenString = tokenHandler.WriteToken(token);48
var result = new49
{50
access_token = tokenString,51
token_type = "Bearer",52
profile = new53
{54
id = user.id,55
name = user.username,56
phone = user.username,57
auth_time = authTime,58
expires_at = expiresAt59
}60
};61
return result;62
}63 64 65
[HttpGet]66
[Route("get_token")]67
public IActionResult Get()68
{69
return Ok(Token(null));70
}71 72
[Authorize(Policy = "IsUser")]73
[Authorize(Policy = "IsAdmin")]74
[Route("get_user_info")]75
[HttpGet]76
public IActionResult GetUserInfo()77
{78
//获取当前请求用户的信息,包含token信息79
var user = HttpContext.User;80 81
return Ok(82
new83
{84
Issuer = base.User.Identity.Name,85
message = "HAHA",86
Issure2 = user.Identity,87
user = user.Claims.Count(),88
user1 = user.Claims.ElementAt(0).Value,89
user2 = user.Claims.ElementAt(1).Value,90
user3 = user.Claims.ElementAt(2).Value,91
user4 = user.Claims.ElementAt(3).Value,92
user5 = user.Claims.ElementAt(4).Value,93
user6 = user.Claims.ElementAt(5).Value,94
user7 = user.Claims.ElementAt(6).Value,95
user8 = user.Claims.ElementAt(7).Value,96
}) ;97
}98
}99
}100 创建token 依赖注入 注入服务 注入服务1 获取信息
这篇关于Asp .net core JWT验证的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-12-06使用Microsoft.Extensions.AI在.NET中生成嵌入向量
- 2024-11-18微软研究:RAG系统的四个层次提升理解与回答能力
- 2024-11-15C#中怎么从PEM格式的证书中提取公钥?-icode9专业技术文章分享
- 2024-11-14云架构设计——如何用diagrams.net绘制专业的AWS架构图?
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#