我有一个自定义AuthorizationHandler
设置,用于检查我的数据库是否有apikey。它工作正常,但我希望能够将数据从它返回到控制器。 apikey具有我希望能够在控制器中使用的属性,因此我希望将在处理程序中使用的apikey对象传递回控制器。
Apikey:
public class ApiKey
{
public string apikeyid { get; set; }
public string uid { get; set; }
public string apikey { get; set; }
public bool isactive { get; set;}
public bool ispaid { get; set; }
public bool ismod { get; set; }
public bool isadmin { get; set; }
}
控制器装饰:
[Authorize(Policy = "ApiKey")]
处理程序:
public class ApiKeyRequirementHandler :
AuthorizationHandler<ApiKeyRequirement>
{
private readonly IHttpContextAccessor _contextAccessor;
private readonly ApplicationDbContext _appContext;
private readonly ILogger<ApiKeyRequirementHandler> _logger;
public ApiKeyRequirementHandler(IHttpContextAccessor contextAccessor, ApplicationDbContext appContext, ILogger<ApiKeyRequirementHandler> logger)
{
_contextAccessor = contextAccessor;
_appContext = appContext;
_logger = logger;
}
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, ApiKeyRequirement requirement)
{
string rawAuthHeader = _contextAccessor.HttpContext.Request.Headers["Authorization"];
//_logger.LogDebug(rawAuthHeader);
if(string.IsNullOrEmpty(rawAuthHeader))
{
return Task.CompletedTask;
}
string[] headers = rawAuthHeader.Split(",");
Dictionary<string, string> authHeaders = new Dictionary<string, string>();
string sentApiKey = "";
foreach(string header in headers)
{
if(header.Contains("APIKEY"))
{
string[] splitHeader = header.Split(" ");
authHeaders.Add(splitHeader[0], splitHeader[1]);
sentApiKey = authHeaders["APIKEY"];
}
}
var searchApiKeys = _appContext.apikey.AsQueryable().Where(a => a.apikey == sentApiKey);
foreach(ApiKey foundKey in searchApiKeys)
{
if(foundKey.apikey == sentApiKey && foundKey.isactive)
{
//can I do something here to pass searchApiKey back?
context.Succeed(requirement);
}
}
return Task.CompletedTask;
}
}