Вопрос

Я работаю на странице пользовательского входа в MVC.NET. Я проверяю входы так:

public bool Login(string login, string password, bool persistent)
{
  var loginEntity = this.AdminRepository.GetLogin(login, password);
  if (loginEntity != null)
  {
    FormsAuthentication.SetAuthCookie(login, persistent);

    HttpContext.Current.Session["AdminId"] = loginEntity.AdminId;
    HttpContext.Current.Session["AdminUsername"] = loginEntity.Username;

  return true;
  }

Затем я украшаю любой контроллер, который нуждается в доступе к администратору с атрибутом фильтра:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
  var ctx = HttpContext.Current;

  // check if session is supported
  if (ctx.Session != null)
  {
    var redirectTargetDictionary = new RouteValueDictionary();

    // check if a new session id was generated
    if (ctx.Session.IsNewSession)
    {
        // If it says it is a new session, but an existing cookie exists, then it must
        // have timed out
        string sessionCookie = ctx.Request.Headers["Cookie"];
        if (((null != sessionCookie) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0)) || null == sessionCookie)
        {
          redirectTargetDictionary = new RouteValueDictionary();
          redirectTargetDictionary.Add("area", "Admin");
          redirectTargetDictionary.Add("action", "LogOn");
          redirectTargetDictionary.Add("controller", "Home");

          filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);
        }
      } else if (SessionContext.AdminId == null) {
        redirectTargetDictionary = new RouteValueDictionary();
        redirectTargetDictionary.Add("area", "Admin");
        redirectTargetDictionary.Add("action", "LogOn");
        redirectTargetDictionary.Add("controller", "Home");

        filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);
      }
    }
    base.OnActionExecuting(filterContext);
}

Я вижу, что после входа у меня есть два печенья:

  1. Aspxauth (с датой истечения срока действия, установленной в «В конце сеанса» (когда упорно не ложь) или (через 30 минут (когда настойчиво устанавливается на True)
  2. и asp.net_sessionId, какое время истечения всегда "в конце сеанса"

Вопрос: Проблема в том, что, несмотря на то, что я установил версию «Упорно» (который установит время истечения срока действия ASPXAuth через 30 мин -что хорошо), моя сеанс [«adminid»] всегда нулевой после того, как я закрываю и вновь открываю браузер. Как я могу убедиться, что мои сеансы (сеанс ["adminid"] и сеанс ["AdminUserName"]) извлечены из файла cookie, когда я изначально установил «сохраняется» к True и Close, а затем вновь откройте окно бродяги. Благодарность

Это было полезно?

Решение 2

Я нашел здесь свое решение:Можно ли использовать .aspxauth для моей собственной системы ведения журнала?

И это то, что я сделал:

    public class SessionExpireFilterAttribute : ActionFilterAttribute
{
    /// <summary>
    /// Controller action filter is used to check whether the session is still active. If the session has expired filter redirects to the login screen.
    /// </summary>
    /// <param name="filterContext"></param>
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var ctx = HttpContext.Current;

        // check if session is supported
        if (ctx.Session != null)
        {
            // check if a new session id was generated
            if (ctx.Session.IsNewSession)
            {
                var identity = ctx.User.Identity;

                // If it says it is a new session, but an existing cookie exists, then it must
                // have timed out
                string sessionCookie = ctx.Request.Headers["Cookie"];
                if (((null != sessionCookie) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0)) || null == sessionCookie)
                {
                    var redirectTargetDictionary = new RouteValueDictionary();
                    redirectTargetDictionary.Add("area", string.Empty);
                    redirectTargetDictionary.Add("action", "LogOn");
                    redirectTargetDictionary.Add("controller", "User");

                    filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);
                }

                // Authenticated user, load session info
                else if (identity.IsAuthenticated)
                {
                    var loginRepository = new LoginRepository(InversionOfControl.Container.Resolve<IDbContext>());
                    IAuthenticationService authenticationService = new AuthenticationService(loginRepository);
                    authenticationService.SetLoginSession(identity.Name);
                }
            }
            else if (SessionContext.LoginId == null)
            {
                var redirectTargetDictionary = new RouteValueDictionary();
                redirectTargetDictionary.Add("area", string.Empty);
                redirectTargetDictionary.Add("action", "LogOn");
                redirectTargetDictionary.Add("controller", "User");

                filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);
            }
        }
        base.OnActionExecuting(filterContext);
    }
}

Другие советы

Печенье со временем истечения записывается на диск. Поэтому пользователь все еще будет войти в систему в следующий раз, когда они откроют браузер, при условии, что файл cookie не истек.

Сеанс cookie хранится только в памяти и теряется, как только браузер закрыт.

Сеанс cookie - это печенье без истечения срока действия.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top