Created
October 11, 2018 12:05
-
-
Save vanillajonathan/3cbffb62bc25e4049d137cab23f096ca to your computer and use it in GitHub Desktop.
Rejects requests not requested over HTTPS.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using Microsoft.AspNetCore.Http; | |
using Microsoft.AspNetCore.Mvc; | |
using Microsoft.AspNetCore.Mvc.Filters; | |
namespace Example.AspNetCore.Mvc | |
{ | |
/// <summary> | |
/// An authorization filter that confirms requests are received over HTTPS. | |
/// </summary> | |
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] | |
public class RequireHttpsApiAttribute : Attribute, IAuthorizationFilter, IOrderedFilter | |
{ | |
/// <inheritdoc /> | |
/// <value>Default is <c>int.MinValue + 50</c> to run this <see cref="IAuthorizationFilter"/> early.</value> | |
public int Order { get; set; } = int.MinValue + 50; | |
/// <summary> | |
/// Called early in the filter pipeline to confirm request is authorized. Confirms requests are received over | |
/// HTTPS. Takes no action for HTTPS requests. | |
/// Otherwise, sets <see cref="AuthorizationFilterContext.Result"/> to a result which will set the status | |
/// code to <c>403</c> (Forbidden). | |
/// </summary> | |
/// <inheritdoc /> | |
public virtual void OnAuthorization(AuthorizationFilterContext filterContext) | |
{ | |
if (filterContext == null) | |
{ | |
throw new ArgumentNullException(nameof(filterContext)); | |
} | |
if (!filterContext.HttpContext.Request.IsHttps) | |
{ | |
filterContext.Result = new StatusCodeResult(StatusCodes.Status403Forbidden); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment