程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> Asp.net mvc 權限過濾和單點登錄(禁止重復登錄)

Asp.net mvc 權限過濾和單點登錄(禁止重復登錄)

編輯:ASP.NET基礎

1.權限控制使用controller和 action來實現,權限方式有很多種,最近開發項目使用控制控制器方式實現代碼如下

/// <summary>
/// 用戶權限控制
/// </summary>
public class UserAuthorize : AuthorizeAttribute
{
  /// <summary>
  /// 授權失敗時呈現的視圖
  /// </summary>
  public string AuthorizationFailView { get; set; }
  /// <summary>
  /// 請求授權時執行
  /// </summary>
  /// <param name="filterContext">上下文</param>
  public override void OnAuthorization(AuthorizationContext filterContext)
  {
    // 獲取url請求裡的 controller 和 action
    string controllerName = filterContext.RouteData.Values["controller"].ToString();
    string actionName = filterContext.RouteData.Values["action"].ToString();
    // 獲取用戶信息
    UserLoginBaseInfo _userLoginInfo = filterContext.HttpContext.Session[Property.UerLoginSession] as UserLoginBaseInfo;
    //根據請求過來的controller和action去查詢可以被哪些角色操作: 這是查詢數據庫 roleid使用 1,2,3,4格式
    RoleWithControllerAction roleWithControllerAction =
      SampleData.roleWithControllerAndAction.FirstOrDefault(r => r.ControllerName.ToLower() == controllerName.ToLower() && r.ActionName.ToLower() == actionName.ToLower() && r.RoleIds.contails("3"));
    // 有值處理
    if (roleWithControllerAction != null)
    {
      //有權限操作當前控制器和Action的角色id
      this.Roles = roleWithControllerAction.RoleIds;
    }
    else
    {
      //請求失敗輸出空結果
      filterContext.Result = new EmptyResult();
      //打出提示文字
      HttpContext.Current.Response.Write("對不起,你沒有權限操作!");
    }
    base.OnAuthorization(filterContext);
  }
  /// <summary>
  /// 自定義授權檢查(返回False則授權失敗)
  /// </summary>
  protected override bool AuthorizeCore(HttpContextBase httpContext)
  {
    //if (httpContext.User.Identity.IsAuthenticated)
    //{
    //  string userName = httpContext.User.Identity.Name;  //當前登錄用戶的用戶名
    //  User user = SampleData.users.Find(u => u.UserName == userName);  //當前登錄用戶對象
    //  if (user != null)
    //  {
    //    Role role = SampleData.roles.Find(r => r.Id == user.RoleId); //當前登錄用戶的角色
    //    foreach (string roleid in Roles.Split(','))
    //    {
    //      if (role.Id.ToString() == roleid)
    //        return true;
    //    }
    //    return false;
    //  }
    //  else
    //    return false;
    //}
    //else
    //  return false;   //進入HandleUnauthorizedRequest
    return true;
  }
  /// <summary>
  /// 處理授權失敗的HTTP請求
  /// </summary>
  protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
  {
    if (string.IsNullOrWhiteSpace(AuthorizationFailView))
      AuthorizationFailView = "error";
    filterContext.Result = new ViewResult { ViewName = AuthorizationFailView };
  }
}

 二.單點登錄方式使用application方式來實現

  1.用戶登錄成功後記錄當前信息

/// <summary>
/// 限制一個用戶只能登陸一次
/// </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();
      //當前用戶已存在移除、
      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.使用ActionFilter來實現單點登錄,每次點擊控制器都去查詢過濾是否在其它地方登錄

/// <summary>
 /// 用戶基礎信息過濾器
 /// </summary>
 public class LoginActionFilter : ActionFilterAttribute
 {
   /// <summary>
   /// 初始化地址
   /// </summary>
   public const string Url = "~/Login/Index?error=";
   /// <summary>
   /// 該方法會在action方法執行之前調用 
   /// </summary>
   /// <param name="filterContext">上下文</param>
   public override void OnActionExecuting(ActionExecutingContext filterContext)
   {
     // 獲取上一級url
     // var url1 = filterContext.HttpContext.Request.UrlReferrer;
     UserLoginBaseInfo _userLogin = filterContext.HttpContext.Session[Property.UerLoginSession] as UserLoginBaseInfo;
     // 用戶是否登陸
     if (_userLogin == null)
     {
       filterContext.Result = new RedirectResult(Url + "登陸時間過期,請重新登陸!&url=" + filterContext.HttpContext.Request.RawUrl);
     }
     else
     {
       filterContext.HttpContext.Session.Timeout = 30;
     }
     //判斷是否在其它地方登錄
     Hashtable singleOnline = (Hashtable)System.Web.HttpContext.Current.Application[Property.Online];
     // 判斷當前SessionID是否存在
     if (singleOnline != null && !singleOnline.ContainsKey(HttpContext.Current.Session.SessionID))
       filterContext.Result = new RedirectResult(Url + "你的帳號已在別處登陸,你被強迫下線!");
     base.OnActionExecuting(filterContext);
   }
   /// <summary>
   /// 執行後
   /// </summary>
   /// <param name="filterContext"></param>
   public override void OnResultExecuting(ResultExecutingContext filterContext)
   {
     //記錄操作日志,寫進操作日志中
     var controllerName = filterContext.RouteData.Values["controller"];
     var actionName = filterContext.RouteData.Values["action"];
     base.OnResultExecuting(filterContext);
   }

 3.用戶正常退出或則非正常退出處理當前用戶信息銷毀Session

/// <summary>
/// Session銷毀
/// </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();
}

以上所述是小編給大家介紹的Asp.net mvc 權限過濾和單點登錄(禁止重復登錄),希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved