.NET 云原生架构师训练营(模块二 基础巩固 安全)--学习笔记
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, // 是否驗證 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});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
課程鏈接
.NET云原生架構師訓練營講什么,怎么講,講多久
歡迎各位讀者加入微信群一起學習交流,
在公眾號后臺回復“加群”即可~~
總結
以上是生活随笔為你收集整理的.NET 云原生架构师训练营(模块二 基础巩固 安全)--学习笔记的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Dapr微服务应用开发系列4:状态管理构
- 下一篇: IdentityServer4之持久化很