【问题标题】:Saving Username into session property to help secure site将用户名保存到会话属性中以帮助保护站点
【发布时间】:2013-01-07 11:22:12
【问题描述】:

编辑 有些人表示不喜欢我在这个问题中提出的特定解决方案,但请不要浪费我的时间建议完全替代的方法。我无法控制我正在从事的工作的要求。如果您不同意并且没有答案,请继续前进。谢谢。

对于初学者来说,这是一个实践项目,不会被公众使用。我需要使用用户名的会话属性来保护我网站中的某些页面。当输入正确的用户名和密码组合时,会发生这种情况(用户名保存到会话中)。老板看了我的实现说“直接把用户名值存入HttpSessionState是不对的,你应该设置session的username属性,把session对象存入HttpSessionState”。现在我想我明白他指的是我的代码的哪些部分,但是更改它会破坏安全性(一旦单个用户登录,任何人都可以使用指向页面的直接链接)。

请务必阅读代码中的 cmets,我添加它们是为了描述有问题的行。

什么在安全方面有效,但用户名直接存储在 HttpSessionState 中:

//login.ascx.cs
private void Login_Click(object sender, EventArgs e)
{
   if (sender == null || e == null)
   {
      throw new ArgumentNullException("Null Exception: Login_Click");
   }

   User user = new User();            
   user.Login(_username.Text, _password.Text);           

   if (user.IsValid() && user.GetIsUser() != false)
   {
      user.Save();
      //the line below is what I used to make the secure pages work properly.
      //but based on what my boss says, I think this is what should be changed.
      Session["Username"] = _username.Text;
      //What i tried instead was to set 'MySession.Current.Username = _username.Text;'
      //which allowed successful login, but the pages became insecure once again.
      Response.Redirect("Secure/Default.aspx");
   }
   else
   {
      DisplayErrors(user._validationErrors);
   }
   _errors.Text = errorMessage;    
}       

和 MySession.cs

public string Username
{
   get
   {
      if (HttpContext.Current.Session["Username"] == null)
      {
         return string.Empty;
      }
      else
      {
         return HttpContext.Current.Session["Username"].ToString();
      }
   }
   set
   {
      //when the line below is uncommented, the secure pages are vulnerable
      //but if I comment it out, they work properly.
      //HttpContext.Current.Session["Username"] = value;
   }
}

那么我如何在Set the username property of the session, and store the session object into the HttpSessionState 保持网站安全的同时保持安全?

编辑:@Win,在 Secure/Default.aspx.cs 中

private void Page_load(object sender, System.EventArgs e)
{
   ...
   if((string)Session["Username"] != _labelusername.Text)
   {
      Response.Redirect(redirectLogin); //to login page
   } 
   else {} //success
}

【问题讨论】:

  • 使用成员身份而非会话身份进行身份验证。
  • 我以为我的第一行已经说得很清楚了,这是一个培训项目,这样做不是项目的一部分,这样做会产生负面影响。将来我很有可能会按照你的方式去做。
  • 我明白这一点,但会员制真的很容易使用,我不明白为什么你会通过做错事来“训练”。会话不能用于存储安全敏感信息,永远。它是用户特定的缓存,仅此而已。切勿将其用于任何类型的身份验证或安全性!
  • MySession.Current.Username = _username.Text;只要它是静态类就有效。您如何在 Secure/Default.aspx 中确保安全?请发布该页面的安全检查代码。
  • 好吧,Win,我用你要求的信息编辑了 OP。

标签: c# asp.net session session-variables


【解决方案1】:

您应该查看FormsAuthentication。网上有很多这样的例子:

http://bradkingsley.com/securing-asp-net-pages-forms-authentication-c-and-net-4/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-04
    • 1970-01-01
    • 1970-01-01
    • 2019-01-01
    相关资源
    最近更新 更多