Skip to content

Instantly share code, notes, and snippets.

@aslamhadi
Last active November 21, 2020 18:48
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 aslamhadi/a080cefe2d91792a34a79ffd9d8ab5b9 to your computer and use it in GitHub Desktop.
Save aslamhadi/a080cefe2d91792a34a79ffd9d8ab5b9 to your computer and use it in GitHub Desktop.
public class RestAuthorizeAttribute : AuthorizeAttribute
{
private const string SecurityToken = "token"; // Name of the header
private readonly IAuthApiService _authApiService = new AuthApiService();
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (Authorize(filterContext))
{
return;
}
HandleUnauthorizedRequest(filterContext);
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
//base.HandleUnauthorizedRequest(filterContext);
var unauthorizedResult = new JsonResult();
var resultJson = new ApiModel(Global.ErrorGetToken, 401, Global.UnAuthorized, null);
unauthorizedResult.Data = resultJson;
unauthorizedResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
filterContext.Result = unauthorizedResult;
}
private bool Authorize(AuthorizationContext actionContext)
{
try
{
HttpRequestBase request = actionContext.RequestContext.HttpContext.Request;
string token = request.Headers[SecurityToken];
return _authApiService.ValidateToken(token);
}
catch (Exception)
{
return false;
}
}
}
@stesvis
Copy link

stesvis commented Nov 21, 2020

Hello, what is AuthApiService?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment