Skip to content

Instantly share code, notes, and snippets.

@thehoneymad
Created August 14, 2015 10:28
Show Gist options
  • Save thehoneymad/c10fec5821c2a618fc8f to your computer and use it in GitHub Desktop.
Save thehoneymad/c10fec5821c2a618fc8f to your computer and use it in GitHub Desktop.
Custom Authorization Attribute on Asp.net web api 2.2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http.Controllers;
using System.Web.Http;
namespace Go_Odin.Lib
{
public class SecureCallAttribute : AuthorizeAttribute
{
private string _reason = "";
public bool ByPassAuthorization { get; set; }
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
if (!string.IsNullOrEmpty(_reason))
actionContext.Response.ReasonPhrase = _reason;
}
private IEnumerable<SecureCallAttribute> GetApiAuthorizeAttributes(HttpActionDescriptor descriptor)
{
return descriptor.GetCustomAttributes<SecureCallAttribute>(true)
.Concat(descriptor.ControllerDescriptor.GetCustomAttributes<SecureCallAttribute>(true));
}
private bool IsSecuredApiCallRequested(HttpActionContext actionContext)
{
var apiAttributes = GetApiAuthorizeAttributes(actionContext.ActionDescriptor);
if (apiAttributes != null && apiAttributes.Any())
return true;
return false;
}
public override void OnAuthorization(HttpActionContext actionContext)
{
if(IsSecuredApiCallRequested(actionContext))
{
var queryParams = actionContext.Request.GetQueryNameValuePairs();
if(queryParams.Any(x=>x.Key.ToLower()=="requestToken") && queryParams.Any(x=>x.Key.ToLower()=="epoch"))
{
this.HandleUnauthorizedRequest(actionContext);
_reason = "Invalid Request , No RequestToken and Epoch";
}
else
{
base.OnAuthorization(actionContext);
}
}
}
protected override bool IsAuthorized(HttpActionContext actionContext)
{
if (ByPassAuthorization || GetApiAuthorizeAttributes(actionContext.ActionDescriptor).Any(x => x.ByPassAuthorization))
return true;
if(!this.IsValidRequestTokenWithEpoch(actionContext.Request.GetQueryNameValuePairs()))
{
this.HandleUnauthorizedRequest(actionContext);
_reason = "Invalid Epoch or RequestToken, Access Denied";
return false;
}
return base.IsAuthorized(actionContext);
}
private bool IsValidRequestTokenWithEpoch(IEnumerable<KeyValuePair<string, string>> QueryParams)
{
throw new NotImplementedException();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment