我正在处理要求,其中我检查了我们的请求标头是否包含Authorization标头,并基于该标头调用另一个Server并返回403。目前,我已经通过创建Custom ActionAttribute来做到这一点:
public class ValidateAuthHeaderAttribute: ActionFilterAttribute
{
private readonly ILogger<ValidateAuthHeaderAttribute> _logger;
public ValidateAuthHeaderAttribute(ILogger<ValidateAuthHeaderAttribute> logger)
{
_logger = logger;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
var httpContext = context.HttpContext;
if (httpContext.Request.Headers.ContainsKey("Authorization"))
{
return;
}
var failureResponse = new FailureResponseModel
{
Result = false,
ResultDetails = "Authorization header not present in request",
Uri = httpContext.Request.Path.ToUriComponent(),
Timestamp = DateTime.Now.ToString("s", CultureInfo.InvariantCulture),
Error = new Error
{
Code = 108,
Description = "Authorization header not present in request",
Resolve = "Send Request with authorization header to avoid this error."
}
};
var responseString = JsonConvert.SerializeObject(failureResponse);
context.Result = new ContentResult
{
Content = responseString,
ContentType = "application/json",
StatusCode = 403
};
}
}
我正在像这样在我的控制器/方法中使用此自定义属性。
[TypeFilter(typeof(ValidateAuthHeaderAttribute))]
现在一切正常,但是我正在阅读有关.Net Core doc中基于策略的授权的信息。因此,现在建议使用策略。我当时想可以将我的代码移植到“自定义策略”中。
答案 0 :(得分:2)
IMO,我建议您继续使用ValidateAuthHeaderAttribute
,这要容易得多。
如果您坚持执行政策,请执行以下步骤:
要求
public class AuthorizationHeaderRequirement: IAuthorizationRequirement
{
}
public class AuthorizationHeaderHandler : AuthorizationHandler<AuthorizationHeaderRequirement>
{
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, AuthorizationHeaderRequirement requirement)
{
// Requires the following import:
// using Microsoft.AspNetCore.Mvc.Filters;
if (context.Resource is AuthorizationFilterContext mvcContext)
{
// Examine MVC-specific things like routing data.
var httpContext = mvcContext.HttpContext;
if (httpContext.Request.Headers.ContainsKey("Authorization"))
{
context.Succeed(requirement);
return;
}
var failureResponse = new FailureResponseModel
{
Result = false,
ResultDetails = "Authorization header not present in request",
Uri = httpContext.Request.Path.ToUriComponent(),
Timestamp = DateTime.Now.ToString("s", CultureInfo.InvariantCulture),
Error = new Error
{
Code = 108,
Description = "Authorization header not present in request",
Resolve = "Send Request with authorization header to avoid this error."
}
};
var responseString = JsonConvert.SerializeObject(failureResponse);
mvcContext.Result = new ContentResult
{
Content = responseString,
ContentType = "application/json",
StatusCode = 403
};
await mvcContext.Result.ExecuteResultAsync(mvcContext);
}
return;
}
}
在Startup.cs
中配置
services.AddAuthorization(options =>
{
options.AddPolicy("AuthorizationHeaderRequirement", policy =>
policy.Requirements.Add(new AuthorizationHeaderRequirement()));
});
services.AddSingleton<IAuthorizationHandler, AuthorizationHeaderHandler>();
控制器
[Authorize(Policy = "AuthorizationHeaderRequirement")]
public IActionResult Privacy()
{
return View();
}