I need to modify user roles in my web api 2 project using Identity 2 by adding additional properties: DateTime StartDate
and DateTime EndDate
. This is required to be able to grant users roles for a limited period of time.
What do I need to do to get the Authorize
attribute such as [Authorize(Role="poweruser")]
etc. to understand the role dates?
According to source (https://github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/System.Web.Http/AuthorizeAttribute.cs) this filter ultimately calls IPrincipal.IsInRole
:
protected virtual bool IsAuthorized(HttpActionContext actionContext)
{
...
if (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole))
{
return false;
}
return true;
}
Looks like I need to subclass the implementation of IPrincipal
in HttpActionContext.ControllerContext.RequestContext.Principal
and somehow inject it somewhere in the life cycle instead of the default implementation.
How do I do this?
Just Create a custom implementation of of AuthorizeAttribute
like UserAuthorize
and instead of using [Authorize(Role="poweruser")]
you will use [UserAuthorize(Role="poweruser")]
.
Your UserAuthorize
implmentation could look like this:
public class UserAuthorizeAttribute : AuthorizeAttribute
{
/// <summary>
/// Validate User Request for selected Feature
/// </summary>
/// <param name="httpContext"></param>
/// <returns></returns>
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if(!isAuthorized) {
return false; //User is Not Even Logged In
}
//Your custom logic here
}