Asp.net如果未登录,则保护文件夹的登录页面重定向

时间:2016-04-21 00:04:59

标签: c# asp.net redirect web-config

如果没有登录,我希望用户被重定向到登录页面。登录凭据是" Admin" &安培; "密码"总是。当我登录时,它会将我重定向到受保护的文件,这正是我想要的。但是,我也可以在不登录的情况下导航到受保护的文件。什么是最佳解决方案?这与我的Web.Config有关吗? Beneath是我的帐户文件夹的授权控件,该文件夹有login.aspx,如果用户无法登录,我想保护文件夹/私人文件。

<location path="Account">
  <system.web>
    <authorization>
        <allow users="?"/>
    </authorization>
 </system.web>
</location>

期待您的帮助!

这是我在登录按钮点击后的Login.aspx事件处理程序:

protected void LogIn(object sender, EventArgs e)
    {


    if (FormsAuthentication.Authenticate(UserName.Text, Password.Text))
    {
        var persistCookie = false;
        FormsAuthentication.RedirectFromLoginPage(UserName.Text, persistCookie);
    }

    if (IsValid)
    {
        string uname = UserName.Text.ToString().Replace(" ", "").ToString();
        string password = Password.Text.ToString().Replace(" ", "").ToString();


        if (String.Equals(uname, "Admin") && String.Equals(password, "MG32015!"))

        {
            Session["user"] = uname;
            Response.Redirect("~/Private/ViewEnquiry.aspx");
            //IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
        }
        else
        {
            FailureText.Text = "Invalid username or password.";
            ErrorMessage.Visible = true;
        }


    }

Logout.aspx.cs有这个:

public partial class Account_Login : Page
{
protected void Page_Load(object sender, EventArgs e)
{
    Session.Clear();
    FormsAuthentication.SignOut();
    //Response.Redirect("Login.aspx");
}



protected void Login_Click(object sender, EventArgs e)
{
    Response.Redirect("~/Account/Login.aspx");

}

}

1 个答案:

答案 0 :(得分:2)

您可以为不同的路径设置不同的配置。确保您拒绝未知用户和#34;私人&#34;。

此外,如果您按照自己的方式做事,最好使用硬编码凭证的标准方式并进行身份验证。

这是配置的样子:

.text

...这里是代码(包括设置身份验证cookie的方法):

<system.web>
  <authentication mode="Forms">
     <forms name=".ASPXFORMSAUTH" loginUrl="/login.aspx">
        <credentials passwordFormat = "Clear">
           <user 
              name="Admin" 
              password="Password"/>
        </credentials>
      </forms>
   </authentication>
</system.web>

<!-- Account -->
<location path="Account">
  <system.web>
    <authorization>
        <allow users="*"/>
    </authorization>
 </system.web>
</location>
<!-- Private -->
<location path="Private">
  <system.web>
    <authorization>
        <deny users="?"/>
    </authorization>
 </system.web>
</location>

另请注意,您可以从cookie访问用户名,而不依赖于会话:

protected void LogIn(Object sender, EventArgs E) 
{
  // authenticate user: this sample authenticates 
  // against users in your app domain's web.config file
  if (FormsAuthentication.Authenticate(UserName.Text,
                                       Password.Text))
  {
    var persistCookie = false;
    //this is what actually sets the auth cookie.
    FormsAuthentication.RedirectFromLoginPage(UserName.Value, persistCookie);
  } 
}