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
課程鏈接
https://appsqsyiqlk5791.h5.xiaoeknow.com/v1/course/video/v_5f39bdb8e4b01187873136cf?type=2
本作品采用知識共享署名-非商業性使用-相同方式共享 4.0 國際許可協議進行許可。
歡迎轉載、使用、重新發布,但務必保留文章署名 鄭子銘 (包含鏈接: http://www.cnblogs.com/MingsonZheng/ ),不得用於商業目的,基於本文修改后的作品務必以相同的許可發布。
如有任何疑問,請與我聯系 (MingsonZheng@outlook.com) 。