Skip to content

Instantly share code, notes, and snippets.

@vanillajonathan
Created October 11, 2018 12:05
Show Gist options
  • Save vanillajonathan/3cbffb62bc25e4049d137cab23f096ca to your computer and use it in GitHub Desktop.
Save vanillajonathan/3cbffb62bc25e4049d137cab23f096ca to your computer and use it in GitHub Desktop.
Rejects requests not requested over HTTPS.
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