Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bschapendonk/966ccac21ce8860ac3afb048e0279c73 to your computer and use it in GitHub Desktop.
Save bschapendonk/966ccac21ce8860ac3afb048e0279c73 to your computer and use it in GitHub Desktop.
using System;
using System.Configuration;
using System.Net;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace WebApplication4
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class PreSharedKeyAuthorizationFilterAttribute : AuthorizationFilterAttribute
{
public string SchemeAppSettingsKey { get; set; }
public string PreSharedKeyAppSettingsKey { get; set; }
public override void OnAuthorization(HttpActionContext actionContext)
{
if (string.IsNullOrWhiteSpace(SchemeAppSettingsKey))
throw new InvalidOperationException($"{nameof(SchemeAppSettingsKey)} IsNullOrWhiteSpace");
if (string.IsNullOrWhiteSpace(PreSharedKeyAppSettingsKey))
throw new InvalidOperationException($"{nameof(PreSharedKeyAppSettingsKey)} IsNullOrWhiteSpace");
var scheme = ConfigurationManager.AppSettings[SchemeAppSettingsKey];
var preSharedKey = ConfigurationManager.AppSettings[PreSharedKeyAppSettingsKey];
var authorization = actionContext.Request.Headers.Authorization;
if (authorization == null
|| !scheme.Equals(authorization.Scheme, StringComparison.OrdinalIgnoreCase)
|| !preSharedKey.Equals(authorization.Parameter, StringComparison.OrdinalIgnoreCase))
{
actionContext.Response = actionContext.ControllerContext.Request.CreateResponse(HttpStatusCode.Forbidden);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment