.NET 云原生架构师训练营(模块二 基础巩固 安全)--学习笔记

2.8 安全

  • 认证 VS 受权
  • ASP .NET Core 认证受权中间件
  • 认证
  • JWT 认证
  • 受权

认证 VS 受权

  • 认证是一个识别用户是谁的过程
  • 受权是一个决定用户能够干什么的过程
  • 401 Unauthorized 未受权
  • 403 Forbidden 禁止访问

ASP .NET Core 认证受权中间件

在接收到请求以后,认证(Authentication)和受权(Authorization) 发生在 路由(Routing) 和 终结点(Endpoint) 之间git

执行过程

认证

认证是一个识别用户是谁的过程github

代码示例

Web api jwt authenticationapi

在 LighterApi 项目的 Startup.cs 中配置添加服务安全

ConfigureServicesapp

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
        });

Configurepost

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

添加标签 [Authorize]spa

[Authorize]
public class ProjectController : ControllerBase

经过 postman 调用接口,返回 401 Unauthorized3d

须要经过登陆接口获取 token,再带上 token 访问code

JWT 认证

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

什么是 JWT

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

  • 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

相关文章
相关标签/搜索