Asp.Net Core安全之认证与授权
1、认证 VS 授权
- 认证是一个识别用户是谁的过程
- 授权是一个决定用户可以干什么的过程
- 401 Unauthorized 代表:未授权
- 403 Forbidden 代表:禁止访问
2、ASP .NET Core 认证授权中间件
在接收到请求之后,认证(Authentication)和授权(Authorization) 发生在 路由(Routing) 和 终结点(Endpoint) 之间
3、代码实现
以JWT为例,在Startup.cs 中配置添加服务
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(Roles = "Administrators, Mentor")]
public class ProjectController : ControllerBase
JWT版发Token
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));