Skip to content

Instantly share code, notes, and snippets.

@Boggin
Created October 17, 2013 15:46
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 Boggin/861977bfc155a82d785e to your computer and use it in GitHub Desktop.
Save Boggin/861977bfc155a82d785e to your computer and use it in GitHub Desktop.
MS Web API Authorize Attribute with Ninject 3.0
namespace Demo.WebMvc4.Infrastructure
{
using System.Web.Http;
public class ApiAuthorizeAttribute : AuthorizeAttribute
{
public Role Permission { get; set; }
// Note: Ninject currently doesn't support filter binding in Web API so this is a workaround.
protected AuthorizationService AuthorizationService
{
get
{
return (AuthorizationService)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IAuthorizationService));
}
}
// Note: Ninject currently doesn't support filter binding in Web API so this is a workaround.
protected PersonManager PersonManager
{
get
{
return (PersonManager)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IPersonManager));
}
}
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
base.OnAuthorization(actionContext);
var user = this.PersonManager.GetCurrentUserFromStore();
var isAuthorized = this.AuthorizationService.Authorize(user, this.Permission);
if (!isAuthorized)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Insufficient permissions.");
}
}
}
}
namespace Demo.Business
{
public class AuthorizationService : IAuthorizationService
{
public bool Authorize(PersonDto user, Role requiredRoles)
{
if ((user.Permissions & Role.Administrator) == Role.Administrator)
{
return true;
}
// Check if the roles enum has the specific role bit set.
return (requiredRoles & user.Permissions) == requiredRoles;
}
}
}
namespace Demo.WebMvc4.Controllers.Api
{
[ApiAuthorize(Permission = Role.Administrator)]
public class CategoryController : ApiController
{
[HttpPost]
public HttpResponseMessage Post(IEnumerable<CategoryDto> categories)
{
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment