杭州模板建站定制网站,巴彦淖尔网站建设,深圳信息网,手机app界面设计模板图片2.8 安全认证 VS 授权ASP .NET Core 认证授权中间件认证JWT 认证授权认证 VS 授权认证是一个识别用户是谁的过程授权是一个决定用户可以干什么的过程401 Unauthorized 未授权403 Forbidden 禁止访问ASP .NET Core 认证授权中间件在接收到请求之后#xff0c;认证#xff08;A… 2.8 安全认证 VS 授权ASP .NET Core 认证授权中间件认证JWT 认证授权认证 VS 授权认证是一个识别用户是谁的过程授权是一个决定用户可以干什么的过程401 Unauthorized 未授权403 Forbidden 禁止访问ASP .NET Core 认证授权中间件在接收到请求之后认证Authentication和授权Authorization 发生在 路由Routing 和 终结点Endpoint 之间执行过程认证认证是一个识别用户是谁的过程代码示例Web api jwt authentication在 LighterApi 项目的 Startup.cs 中配置添加服务ConfigureServicesservices.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options options.TokenValidationParameters new TokenValidationParameters{ValidateIssuer true, // 是否验证 IssuerValidateAudience true, // 是否验证 AudienceValidateLifetime true, // 是否验证失效时间ClockSkew TimeSpan.FromSeconds(30),ValidateIssuerSigningKey true, // 是否验证 SecurityKeyValidAudience https://localhost:6001,ValidIssuer https://localhost:6001,IssuerSigningKey new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret88secret666)) // 拿到 SecurityKey});
Configureapp.UseAuthentication();
app.UseAuthorization();
添加标签 [Authorize][Authorize]
public class ProjectController : ControllerBase
通过 postman 调用接口返回 401 Unauthorized需要通过登录接口获取 token再带上 token 访问JWT 认证什么是 JWT颁发 token 代码示例什么是 JWTJWT 是一个 token由三部分组成格式为 xxx.yyy.zzzHeaderalgorithm typePayloadclaimsSingature颁发 token 代码示例namespace LighterApi.Controller
{[ApiController][Route(api/[controller])]public class IdentityController : ControllerBase{[HttpPost][Route(signin)]public IActionResult SignIn(){var securityKey new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret88secret666));var credentials new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);var token new JwtSecurityToken(issuer: https://localhost:6001,audience: https://localhost:6001,new ListClaim {new Claim(name, mingson)},expires: DateTime.Now.AddMinutes(120),signingCredentials: credentials);return Ok(new JwtSecurityTokenHandler().WriteToken(token));}}
}
启动程序访问接口获取 token通过官网解析带上 token 访问接口授权为接口添加访问需要的角色具备角色才能访问[Authorize(Roles Administrators, Mentor)]
SignIn 接口返回 token 中加入角色new Claim(ClaimTypes.Role, Administrators),
启动程序获取包含角色的 token带上 token 访问需要角色的接口GitHub源码链接https://github.com/MINGSON666/Personal-Learning-Library/tree/main/ArchitectTrainingCamp/LighterApi课程链接.NET云原生架构师训练营讲什么怎么讲讲多久欢迎各位读者加入微信群一起学习交流在公众号后台回复“加群”即可~~