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 中配置添加服务

ConfigureServices

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 = "https://localhost:6001",
ValidIssuer = "https://localhost:6001",
IssuerSigningKey =
new SymmetricSecurityKey(Encoding.UTF8.GetBytes("secret88secret666")) // 拿到 SecurityKey
});

Configure

app.UseAuthentication();
app.UseAuthorization();

添加标签 [Authorize]

[Authorize]
public class ProjectController : ControllerBase

通过 postman 调用接口,返回 401 Unauthorized

需要通过登录接口获取 token,再带上 token 访问

JWT 认证

  • 什么是 JWT
  • 颁发 token 代码示例

什么是 JWT

JWT 是一个 token,由三部分组成,格式为 xxx.yyy.zzz

  • Header(algorithm + type)
  • Payload(claims)
  • Singature

颁发 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 List<Claim> {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

最新文章

  1. NOIP2004火星人
  2. js设计模式总结-单例模式
  3. Jquery全选单选功能
  4. mongodb_修改器($inc/$set/$unset/$push/$pop/upsert......)
  5. Android:res之layer-list的用法
  6. Java server数据之(4):Redis鸟瞰
  7. hadoop wordcount
  8. GoldenGate 之 Bounded Recovery说明
  9. CentOS 6.6 yum 方式安装sunversion 服务器
  10. Android开发者指南-方位传感器-Position Sensor
  11. [Windwos Phone] 实作地图缩放 MapAnimationKind 属性效果
  12. mybatis-generator 根据表生成对应文件
  13. Photoshop快速给美女人像换头发
  14. [Linux] deepin15.8搭建LNMP环境
  15. Monte Carlo simulated annealing
  16. 002-pro ant design-Unexpected end of JSON input while parsing near &#39;...错误解决方案
  17. protected
  18. stingray后端开发
  19. 转:未能打开编辑器:Unmatched braces in the pattern.
  20. 记dynamic的一个小坑 -- RuntimeBinderException:“object”未包括“xxx”的定义

热门文章

  1. Kubernetes --(k8s)yml 文件
  2. poj 1511-- Invitation Cards (dijkstra+优先队列)
  3. HDU3544 Alice&#39;s Game &amp;&amp; POJ 2960 S-Nim(SG函数)
  4. 营业额统计 HYSBZ - 1588
  5. 树状数组 &amp;&amp; 板子
  6. Codeforces Round #658 (Div. 2) D. Unmerge (思维,01背包)
  7. SpringBoot简单整合redis
  8. oslab oranges 一个操作系统的实现 实验四 认识保护模式(三):中断异常
  9. 局部变量 static new 结构体指针
  10. redis运维与开发笔记