Asp. net mvc Permission Filtering and Single Sign on (No Duplicate Logon)

  • 2021-08-31 07:40:49
  • OfStack

1. The authority control uses controller and action to realize, the authority way has many kinds, the recent development project uses the control controller way to realize the code as follows


/// <summary>
///  User rights control 
/// </summary>
public class UserAuthorize : AuthorizeAttribute
{
  /// <summary>
  ///  View rendered when authorization fails 
  /// </summary>
  public string AuthorizationFailView { get; set; }
  /// <summary>
  ///  Executed when authorization is requested 
  /// </summary>
  /// <param name="filterContext"> Context </param>
  public override void OnAuthorization(AuthorizationContext filterContext)
  {
    //  Get url In the request  controller  And  action
    string controllerName = filterContext.RouteData.Values["controller"].ToString();
    string actionName = filterContext.RouteData.Values["action"].ToString();
    //  Get user information 
    UserLoginBaseInfo _userLoginInfo = filterContext.HttpContext.Session[Property.UerLoginSession] as UserLoginBaseInfo;
    // Coming on request controller And action To query which roles can be operated by :  This is the query database  roleid Use  1,2,3,4 Format 
    RoleWithControllerAction roleWithControllerAction =
      SampleData.roleWithControllerAndAction.FirstOrDefault(r => r.ControllerName.ToLower() == controllerName.ToLower() && r.ActionName.ToLower() == actionName.ToLower() && r.RoleIds.contails("3"));
    //  Value processing 
    if (roleWithControllerAction != null)
    {
      // Have permission to manipulate the current controller and Action The role of id
      this.Roles = roleWithControllerAction.RoleIds;
    }
    else
    {
      // Request failed and output null result 
      filterContext.Result = new EmptyResult();
      // Type prompt text 
      HttpContext.Current.Response.Write(" I'm sorry , You don't have permission to operate !");
    }
    base.OnAuthorization(filterContext);
  }
  /// <summary>
  ///  Custom Authorization Check (Returns False Authorization fails) 
  /// </summary>
  protected override bool AuthorizeCore(HttpContextBase httpContext)
  {
    //if (httpContext.User.Identity.IsAuthenticated)
    //{
    //  string userName = httpContext.User.Identity.Name;  // The user name of the currently logged-in user 
    //  User user = SampleData.users.Find(u => u.UserName == userName);  // Current Logon User Object 
    //  if (user != null)
    //  {
    //    Role role = SampleData.roles.Find(r => r.Id == user.RoleId); // Role of the currently logged-in user 
    //    foreach (string roleid in Roles.Split(','))
    //    {
    //      if (role.Id.ToString() == roleid)
    //        return true;
    //    }
    //    return false;
    //  }
    //  else
    //    return false;
    //}
    //else
    //  return false;   // Enter HandleUnauthorizedRequest
    return true;
  }
  /// <summary>
  ///  Object that handles authorization failures HTTP Request 
  /// </summary>
  protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
  {
    if (string.IsNullOrWhiteSpace(AuthorizationFailView))
      AuthorizationFailView = "error";
    filterContext.Result = new ViewResult { ViewName = AuthorizationFailView };
  }
}

2. The single sign-on mode is implemented by application mode

1. Record the current information after the user logs in successfully


/// <summary>
///  Limit 1 Users can only log in 1 Times 
/// </summary>
/// <returns></returns>
private void GetOnline()
{
  string UserID = "1";
  Hashtable SingleOnline = (Hashtable)System.Web.HttpContext.Current.Application[Property.Online];
  if (SingleOnline == null)
    SingleOnline = new Hashtable();
  IDictionaryEnumerator idE = SingleOnline.GetEnumerator();
  string strKey = string.Empty;
  while (idE.MoveNext())
  {
    if (idE.Value != null && idE.Value.ToString().Equals(UserID))
    {
      //already login 
      strKey = idE.Key.ToString();
      // The current user already exists for removal, 
      SingleOnline.Remove(strKey);
      System.Web.HttpContext.Current.Application.Lock();
      System.Web.HttpContext.Current.Application[Property.Online] = SingleOnline;
      System.Web.HttpContext.Current.Application.UnLock();
      break;
    }
  }
  //SessionID
  if (!SingleOnline.ContainsKey(Session.SessionID))
  {
    SingleOnline[Session.SessionID] = UserID;
    System.Web.HttpContext.Current.Application.Lock();
    System.Web.HttpContext.Current.Application[Property.Online] = SingleOnline;
    System.Web.HttpContext.Current.Application.UnLock();
  }
}

2. Use ActionFilter to realize single sign-on. Every time you click on the controller, you will query whether the filter logs in elsewhere


/// <summary>
 ///  User Basic Information Filter 
 /// </summary>
 public class LoginActionFilter : ActionFilterAttribute
 {
   /// <summary>
   ///  Initialization address 
   /// </summary>
   public const string Url = "~/Login/Index?error=";
   /// <summary>
   ///  This method will be used in the action Called before the method executes  
   /// </summary>
   /// <param name="filterContext"> Context </param>
   public override void OnActionExecuting(ActionExecutingContext filterContext)
   {
     //  Get on 1 Grade url
     // var url1 = filterContext.HttpContext.Request.UrlReferrer;
     UserLoginBaseInfo _userLogin = filterContext.HttpContext.Session[Property.UerLoginSession] as UserLoginBaseInfo;
     //  Does the user log in 
     if (_userLogin == null)
     {
       filterContext.Result = new RedirectResult(Url + " Log-in time expired , Please log in again !&url=" + filterContext.HttpContext.Request.RawUrl);
     }
     else
     {
       filterContext.HttpContext.Session.Timeout = 30;
     }
     // Determine whether to log in elsewhere 
     Hashtable singleOnline = (Hashtable)System.Web.HttpContext.Current.Application[Property.Online];
     //  Judge the current SessionID Does it exist 
     if (singleOnline != null && !singleOnline.ContainsKey(HttpContext.Current.Session.SessionID))
       filterContext.Result = new RedirectResult(Url + " Your account has been logged in elsewhere, and you are forced to log off !");
     base.OnActionExecuting(filterContext);
   }
   /// <summary>
   ///  After execution 
   /// </summary>
   /// <param name="filterContext"></param>
   public override void OnResultExecuting(ResultExecutingContext filterContext)
   {
     // Record the operation log and write it into the operation log 
     var controllerName = filterContext.RouteData.Values["controller"];
     var actionName = filterContext.RouteData.Values["action"];
     base.OnResultExecuting(filterContext);
   }

3. If the user exits normally or abnormally, process the current user information and destroy Session


/// <summary>
/// Session Destruction 
/// </summary>
protected void Session_End()
{
  Hashtable SingleOnline = (Hashtable)Application[Property.Online];
  if (SingleOnline != null && SingleOnline[Session.SessionID] != null)
  {
    SingleOnline.Remove(Session.SessionID);
    Application.Lock();
    Application[Property.Online] = SingleOnline;
    Application.UnLock();
  }
  Session.Abandon();
}

The above is the site to introduce you Asp. net mvc rights filtering and single sign-on (no repeated login), I hope to help you, if you have any questions welcome to leave me a message, this site will reply to you in time!


Related articles: