feat: 后端添加管理员认证
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
@@ -61,6 +62,15 @@ try
|
||||
options.Authority = "http://localhost:5000";
|
||||
options.RequireHttpsMetadata = false;
|
||||
});
|
||||
builder.Services.AddAuthorization(options =>
|
||||
{
|
||||
options.AddPolicy("Admin", policy =>
|
||||
{
|
||||
policy.RequireClaim(ClaimTypes.Role, new string[] {
|
||||
Database.User.UserPermission.Admin.ToString(),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// Add CORS policy
|
||||
if (builder.Environment.IsDevelopment())
|
||||
@@ -159,6 +169,7 @@ try
|
||||
app.UseHttpsRedirection();
|
||||
app.UseRouting();
|
||||
app.UseCors();
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
// Swagger
|
||||
|
@@ -69,6 +69,7 @@ public class DataController : ControllerBase
|
||||
{
|
||||
new Claim(ClaimTypes.Name, user.Name),
|
||||
new Claim(ClaimTypes.Email, user.EMail),
|
||||
new Claim(ClaimTypes.Role, user.Permission.ToString())
|
||||
}),
|
||||
Expires = DateTime.UtcNow.AddHours(1),
|
||||
SigningCredentials = new SigningCredentials(
|
||||
@@ -96,6 +97,20 @@ public class DataController : ControllerBase
|
||||
return Ok("认证成功!");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 测试管理员用户认证,需携带有效 JWT
|
||||
/// </summary>
|
||||
/// <returns>认证成功信息</returns>
|
||||
[Authorize("Admin")]
|
||||
[HttpGet("TestAdminAuth")]
|
||||
[EnableCors("Users")]
|
||||
[ProducesResponseType(typeof(string), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
|
||||
public IActionResult TestAdminAuth()
|
||||
{
|
||||
return Ok("认证成功!");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取当前用户信息
|
||||
/// </summary>
|
||||
|
Reference in New Issue
Block a user