Hi All,
In many of our scenario's we need to use Authorize Attribute in our MVC project. The limitation of which is just that we can't use our custom user roles. What if we intend to use custom enum to Authorize some of our Action Methods. Below is a simple and effective way of achieving this.
Step 1 - We will create enum for user Types:
public enum userType
{
User1,
User2,
User3,
User4
}
Step 2 - Create a SiteSession Class that will hold the session of the loggedIn User:
public class SiteSession
{
public static LoginModel SessionMember
{
get { return (LoginModel)HttpContext.Current.Session["SessionMember"]; }
set { HttpContext.Current.Session["SessionMember"] = value; }
}
public static userType SessionUserType
{
get { return (userType)HttpContext.Current.Session["SessionUserType"]; }
set { HttpContext.Current.Session["SessionUserType"] = value; }
}
}
Also, Add userType enum as one of the property in your LoginModel.
Step 3 - We will override default Authorize Attribute to accept this enum and authorize accordingly:
public class UserAuthorizeAttribute : AuthorizeAttribute
{
private readonly userType allowedUserType;
public UserAuthorizeAttribute(userType UserType)
{
this.allowedUserType = UserType;
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
SiteSession.SessionUserType = this.allowedUserType;
bool authorize = false;
if (SiteSession.SessionMember != null)
authorize = SiteSession.SessionMember.UserType == this.allowedUserType ? true : false;
if(!authorize)
{
FormsAuthentication.SignOut();
SiteSession.SessionMember = null;
}
return authorize;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new HttpUnauthorizedResult();
}
}
Step 4 - Will use this UserAuthorizeAttribute to authorize certain user Type:
To do this use
[UserAuthorize(userType.User1)]
above your controller or Action Method that you need to authorize for users of type User1.
And this will authorize your user as you want.
Happy Coding....
0 Comment(s)