【问题标题】:How to properly implement user system for sessions如何正确实现会话的用户系统
【发布时间】:2011-01-27 16:28:27
【问题描述】:

我以前从未真正实现过注册/登录系统,所以我尝试在 C#/ASP.NET 中创建自己的系统(不使用 ASP.NET 的内置成员资格提供程序)。我有点不清楚的是如何利用 Session/cookies 让用户在会话期间和会话之间保持登录状态。

protected void Login_User(object sender, EventArgs e)
{
    string username = usernameField.Text;
    string password = passwordField.Text;
    User user = UserRepository.FindUser(username);
    if (user != null)
    {
        if (user.Password.Equals(Hash(password)))
        {
            // How do I properly login the user and keep track of his session?
        }
        else
            Response.Write("Wrong password!");
    }
    else 
        Response.Write("User does not exist!");
}

【问题讨论】:

  • 希望这不会用于生产代码?
  • 这当然是为了学习。

标签: c# asp.net session membership


【解决方案1】:

正确的登录系统相当复杂。

  1. 创建继承 System.Security.Principal.IPrincipal 的类
  2. 另一个继承 System.Security.Principal.IIdentity 的类
  3. 将 IPrincipal 派生分配给 System.Web.HttpConext.Current.User
  4. 如果您不想使用 cookie,请将您的 IPrincipal 放入 Session。
  5. 如果 HttpContext.Current.User 丢失,则通过从会话中获取重新分配(在第一个事件中,例如 page_init)。对于我的代码,我使用 FormsAuthenticationTicket 作为 cookie 并在 Global.asax 上重新分配 PostAuthenticateRequest 事件

使用 HttpContext.Current.User 的好处是你可以标记方法属性。

[Authorize] // authorized user only
public void btn_click(...){...}

我不确定普通的 asp.net,但它在 asp MVC 中工作得很好

如果你想使用 cookie,试试 System.Web.Securitiy.FormsAuthenticationTicket 和 FormsAuthentication

样本

public class WebUser:System.Security.Principal.IPrincipal
{
  ...
  public System.Security.Principal.IIdentity Identity{get; private set;}
  public WebUser(...)
  {
    this.Identity = new WebIdentity(...);
    HttpContext.Current.User = this;
  }
}
public class WebIdentity : System.Security.Principal.IIdentity
{
  ...
}

public void Login(...)
{
  var newUser = new WebUser(...);
}

【讨论】:

  • 在哪里重新分配 HttpContext.Current.User?我尝试使用 global.asax 中的 Application_AuthenticateRequest 事件来检查每个请求,但此事件中不存在会话。
  • 我在 PostAuthenticateRequest(global.asax) 分配。只需将 HttpContext.Current.User = new WebUser(...);无需分配给会话
【解决方案2】:

您可以使用RedirectFromLogin 重定向到用户请求但由于身份验证而无法访问的页面,或者如果您想控制用户重定向到的位置,您可以使用SetAuthCookie

【讨论】:

    【解决方案3】:

    使用这个:

    public class FormsAuthenticationService 
    {
        public void SignIn(string userName, bool createPersistentCookie)
        {
            if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
    
            FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
        }
    
        public void SignOut()
        {
            FormsAuthentication.SignOut();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-07-31
      • 2017-04-06
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      • 2020-06-25
      • 2012-09-05
      • 1970-01-01
      • 2012-07-18
      相关资源
      最近更新 更多