I am working on requirement In which I have check whether our request header contains Authorization header and based on that either call another Server and return 403. Currently I have done it by creating Custom ActionAttribute like this:
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
};
}
}
And I am using this Custom Attribute in my Controller/Methods like this.
[TypeFilter(typeof(ValidateAuthHeaderAttribute))]
Now this is working fine, But I was reading about Policy Based Authorization in .Net Core doc. So as it is recommended now to use Policies. I was thinking it is possible to port my code to Custom Policy.