Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@yushiro
Forked from thehoneymad/SecureCallAttribute.cs
Created January 9, 2020 08:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yushiro/db90f1e8c67bf1629565f2c5fffed2ac to your computer and use it in GitHub Desktop.
Save yushiro/db90f1e8c67bf1629565f2c5fffed2ac 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