Skip to content

Instantly share code, notes, and snippets.

@jmprado
Last active August 29, 2015 14:15
Show Gist options
  • Save jmprado/8d45e0b284524d0aa6ca to your computer and use it in GitHub Desktop.
Save jmprado/8d45e0b284524d0aa6ca to your computer and use it in GitHub Desktop.
RequireRolesAttribute.cs
//USAGE
// [RequireRoles(RoleToCheckFor = "Administrador,Editor")]
// public class NumeroPeriodicoController : Controller
// { ... }
//ATENTION
// DO NOT FORGET TO PASS THE USER PROFILE IN THE FORMS AUTHENTICATION PASS IN:
// FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, Email, DateTime.Now,
// DateTime.Now.AddMinutes(2881), false, USER_PROFILE, FormsAuthentication.FormsCookiePath);
public class RequireRolesAttribute : ActionFilterAttribute
{
public string RoleToCheckFor { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//redirect if the user is not authenticated
if (!String.IsNullOrEmpty(RoleToCheckFor))
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
//use the current url for the redirect
string redirectOnSuccess = filterContext.HttpContext.Request.Url.AbsolutePath;
//send them off to the login page
string redirectUrl = string.Format("?ReturnUrl={0}", redirectOnSuccess);
string loginUrl = FormsAuthentication.LoginUrl + redirectUrl;
filterContext.HttpContext.Response.Redirect(loginUrl, true);
}
else
{
FormsIdentity identity = (FormsIdentity)filterContext.HttpContext.User.Identity;
FormsAuthenticationTicket ticket = identity.Ticket;
string actualRole = ticket.UserData;
bool isAuthorized = false;
string[] roles = RoleToCheckFor.Split(',');
for (int i = 0; i < roles.Length; i++)
{
if (filterContext.HttpContext.User.IsInRole(roles[i].Trim()))
isAuthorized = true;
}
if (!isAuthorized)
throw new UnauthorizedAccessException("Falha de autorização! Seu perfil não permite acessar a página ou ação requisitada.");
}
}
else
{
throw new InvalidOperationException("Usuário sem perfil especificado");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment