24 lines
969 B
C#
24 lines
969 B
C#
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.Mvc.Filters;
|
|
|
|
namespace MiaoJiZhang.Api.Services;
|
|
|
|
/// <summary>
|
|
/// 管理后台鉴权:请求头 X-Admin-Key 与 appsettings.Admin:Key 匹配即可。
|
|
/// 仅内部使用,不依赖 JWT/用户体系。
|
|
/// </summary>
|
|
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
|
|
public class AdminAuthAttribute : Attribute, IAuthorizationFilter
|
|
{
|
|
public void OnAuthorization(AuthorizationFilterContext context)
|
|
{
|
|
var config = context.HttpContext.RequestServices.GetRequiredService<IConfiguration>();
|
|
var key = config["Admin:Key"];
|
|
if (string.IsNullOrWhiteSpace(key) ||
|
|
!context.HttpContext.Request.Headers.TryGetValue("X-Admin-Key", out var provided) ||
|
|
provided != key)
|
|
{
|
|
context.Result = new UnauthorizedObjectResult(new { error = "admin_key_required", message = "请在 Header 中提供 X-Admin-Key" });
|
|
}
|
|
}
|
|
} |