我有两个ASP.NET页面:site.com/foo/bar.aspx
应该是世界可访问的,site.com/foo/baz.aspx
我想要密码保护。我希望任何未经过身份验证的用户都能看到用户名/密码页面,然后,一旦他们通过,我希望他们看到真实的东西。我正在寻找最简单的解决方案(this看起来很好,直到它声明要求我移动东西),即使以牺牲灵活性为代价。
我希望看到的是一个控件,如果用户通过身份验证则不执行任何操作,如果不是,则使用登录提示替换“所有”其他控件。
我目前是唯一拥有帐户的用户,因此我现在可以使用硬编码密码列表(而且我或多或少地坚持使用它,因为我没有其他地方可以使用它)
使用Greg's回答我能够使个人页面受密码保护。使用Joel Coehoorn's Link我将其设置为执行表单身份验证。从this page我使用的自定义登录逻辑如下所示:
Login1.Authenticate += new AuthenticateEventHandler(Login1_Authenticate);
...
void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
e.Authenticated = (Login1.UserName == "user" &&
Login1.Password == "password");
}
所有这些放在一起似乎工作正常。 :)
答案 0 :(得分:4)
在这种情况下,最简单的事情可能是forms authentication。您只需将所有内容挂钩到web.config文件和build a simple login page using the pre-built controls。
答案 1 :(得分:1)
您是否在Windows网络上?您可以通过web.config使用Windows身份验证。
这样的事情会起作用:
<system.web>
<authentication mode="Windows" />
</system.web>
<location path="page.aspx">
<system.web>
<authorization>
<allow roles="domain\role"/>
<deny users="*" />
</authorization>
</system.web>
</location>
编辑:好的,不使用Windows网络。这可能会帮助您使用简单和脏的单用户方法:http://www.codeproject.com/Messages/1772445/Setting-username-passwords-in-the-web-config-using-forms-authentication.aspx
答案 2 :(得分:1)
如果您真的只有一个页面,请使用多视图。
<asp:MultiView ID="mvSecretContent" runat="server">
<asp:View ID="viewLogin" runat="server">
<asp:Label AssociatedControlID="username"
runat="server">Username:</asp:Label>
<asp:TextBox ID="username" runat="server"></asp:TextBox>
<asp:Label AssociatedControlID="password"
runat="server">Password:</asp:Label>
<asp:TextBox ID="password" runat="server"></asp:TextBox>
<br />
<asp:Button ID="login" runat="server" OnClick="login_Click"
Text="Log In" />
</asp:View>
<asp:View ID="viewSecret" runat="server">
<h1>This is secret information!</h1>
<asp:Button ID="logout" runat="server" OnClick="logout_Click"
Text="Log Out" />
</asp:View>
</asp:MultiView>
protected void Page_PreRender(object sender, EventArgs e)
{
if (ViewState["IsAuthenticated"] == null ||
!(bool)ViewState["IsAuthenticated"])
{
mvSecretContent.SetActiveView(viewLogin);
}
else
{
mvSecretContent.SetActiveView(viewSecret);
}
}
protected void login_Click(object sender, EventArgs e)
{
// authenticate user/pass
ViewState["IsAuthenticated"] = true;
}
protected void logout_Click(object sender, EventArgs e)
{
ViewState["IsAuthenticated"] = false;
}
它仅存储在ViewState
中,因此您每次访问该页面时都必须重新进行身份验证。如果您将ViewState
更改为Session
,那么无论您的会话设置多长时间都会坚持(默认通常为20分钟)。
答案 3 :(得分:0)
这是BCS对Joel回答的评论的后续跟进:
您需要创建一个Login.aspx表单,但这非常简单:How To: Create an ASP.NET Login Page