如果用户未登录,我希望将其重定向到登录页面。登录凭据为"Admin"&始终使用"密码"。当我登录时,它会将我重定向到受保护的文件,这正是我想要的。但是,我也可以在不登录的情况下导航到受保护的文件。什么是最好的解决方案?这与我的Web.Config有关吗?下面是我对我的帐户文件夹的授权控制,该文件夹有login.aspx,如果用户无法登录,我想保护我的文件夹/Private中的文件。
<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上有这样的内容:
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");
}
}
您可以对不同的路径进行不同的配置。请确保拒绝未知用户进入"私人"。
此外,如果你要按照自己的方式做事,最好使用硬编码凭据和身份验证的标准方式。
配置如下:
<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);
}
}
还要注意,您可以从cookie中访问用户名,而无需依赖会话:
HttpContext.Current.User.Identity.Name