Skip to content

Instantly share code, notes, and snippets.

@winsonet
Created November 9, 2019 03:58
Show Gist options
  • Save winsonet/179b165a274bde4120125514bd926748 to your computer and use it in GitHub Desktop.
Save winsonet/179b165a274bde4120125514bd926748 to your computer and use it in GitHub Desktop.
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
//get the current action for check the accessright
var currentAction = filterContext.RouteData.Values["Action"];
bool ignore = false;
//check login status
if (filterContext.HttpContext.Session["IsLogin"] == null && currentAction != null)
{
//get the current url for redirect after login
filterContext.HttpContext.Session["ReturnAction"] = HttpContext.Current.Request.Url.AbsoluteUri;
UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext);
//if session timeout or lost, then clear all sessions
filterContext.HttpContext.Session.Clear();
//redirect to the login page if session is timeout
var redirectUrl = url.RouteUrl(new { Controller = "Home", Action = "Login" });
HttpContext.Current.Response.Redirect(redirectUrl);
}
//check the allow actions, if this is allow actions, then will ignore the access right checking
if (!string.IsNullOrEmpty(_allowActions) && _allowActions.Contains(currentAction.ToString()))
{
ignore = true;
}
//if set not allow roles
if (!string.IsNullOrEmpty(_notAllowRoles) && !ignore)
{
//if user not allow to access then will redirect to the denied page
if (_notAllowRoles.Contains(filterContext.HttpContext.Session["UserRole"]))
{
filterContext.Result = new RedirectToRouteResult(new
RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));
return;
}
}
//this Roles is inerit AuthorizeAttribute, if set it then will be allow to access
if (!string.IsNullOrEmpty(this.Roles))
{
//check accessright by user role
if ((!HasAccessRights(this.Roles, filterContext.HttpContext.Session["UserRole"])) && !ignore)
{
filterContext.Result = new RedirectToRouteResult(new
RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));
}
}
/// <summary>
/// Check the access rights whether is allow
/// </summary>
/// <param name="roles"></param>
/// <param name="currUserRoles"></param>
/// <returns></returns>
private bool HasAccessRights(string roles, string currUserRoles)
{
if (string.IsNullOrEmpty(currUserRoles))
{
return false;
}
var uRoles = roles.Split(',');
foreach (var role in uRoles)
{
if (currUserRoles.Contains(role))
{
return true;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment