ASP.Net/Login Security/FormsAuthentication — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 14:51, 26 мая 2010
Содержание
- 1 assigning a name to the user accessing next pages
- 2 Checking credentials in SQL Server (C#)
- 3 Checking credentials in SQL Server (VB)
- 4 FormsAuthentication.Authenticate (C#)
- 5 FormsAuthentication.RedirectFromLoginPage (VB)
- 6 FormsAuthentication.SignOut()
- 7 Hash password
- 8 Save user account to an XML file
assigning a name to the user accessing next pages
<source lang="csharp">
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">
<title>Please, log in</title>
</head> <body>
<asp:label runat="server" id="errorMsg"/>
<form id="Form1" runat="server">
User ID | <asp:textbox runat="server" text="" id="userName" /> |
Password | <asp:textbox runat="server" text="" id="passWord" textmode="password" /> |
<asp:button ID="Button1" runat="server" text="Log In..." onclick="LogonUser" /> </form>
</body> </html> File: Login.aspx.cs using System; using System.Data; using System.Configuration; using System.Web.Security; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls;
public partial class Default : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) { SetFocus("userName"); } protected void LogonUser(object sender, EventArgs e) { bool bAuthenticated = false; string user = userName.Text; string pswd = passWord.Text; // Custom authentication bAuthenticated = AuthenticateUser(user, pswd); if (bAuthenticated) FormsAuthentication.RedirectFromLoginPage(user, false); else errorMsg.Text = "Sorry, that"s not it."; } private bool AuthenticateUser(string username, string pswd) { // No authentication--just trust everyone! return true; }
}
</source>
Checking credentials in SQL Server (C#)
<source lang="csharp">
<%@ Page Language="C#"%> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> <script runat="server">
protected void Button1_Click(object sender, EventArgs e) { SqlConnection conn; SqlCommand cmd; string cmdString = "SELECT [Password] FROM [AccessTable] WHERE" + " (([Username] = @Username) AND ([Password] = @Password))"; conn = new SqlConnection("Data Source=localhost;Initial " + "Catalog=Northwind;Persist Security Info=True;User ID=sa"); cmd = new SqlCommand(cmdString, conn); cmd.Parameters.Add("@Username", SqlDbType.VarChar, 50); cmd.Parameters["@Username"].Value = TextBox1.Text; cmd.Parameters.Add("@Password", SqlDbType.VarChar, 50); cmd.Parameters["@Password"].Value = TextBox2.Text; conn.Open(); SqlDataReader myReader; myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); if (myReader.Read()) { FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, false); } else { Response.Write("Invalid credentials"); } myReader.Close(); }
</script>
</source>
Checking credentials in SQL Server (VB)
<source lang="csharp">
<%@ Page Language="VB" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> <script runat="server">
Protected Sub Button1_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Dim conn As SqlConnection Dim cmd As SqlCommand Dim cmdString As String = "SELECT [Password] FROM [AccessTable] WHERE(([Username] = @Username) AND ([Password] = @Password))" conn = New SqlConnection("Data Source=localhost;Initial Catalog=Northwind;Persist Security Info=True;User ID=sa") cmd = New SqlCommand(cmdString, conn) cmd.Parameters.Add("@Username", SqlDbType.VarChar, 50) cmd.Parameters("@Username").Value = TextBox1.Text cmd.Parameters.Add("@Password", SqlDbType.VarChar, 50) cmd.Parameters("@Password").Value = TextBox2.Text conn.Open() Dim myReader As SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection) If myReader.Read() Then FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, False) Else Response.Write("Invalid credentials") End If myReader.Close() End Sub
</script>
</source>
FormsAuthentication.Authenticate (C#)
<source lang="csharp">
<%@ Page Language="C#"%> <script runat="server">
protected void Button1_Click(object sender, EventArgs e) { if (FormsAuthentication.Authenticate(TextBox1.Text, TextBox2.Text)) { FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, true); } else { Response.Write("Invalid credentials"); } }
</script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">
<title>Login Page</title>
</head> <body>
<form id="form1" runat="server">
Username
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
Password
<asp:TextBox ID="TextBox2" runat="server" TextMode="Password"></asp:TextBox>
<asp:Button ID="Button1" OnClick="Button1_Click" runat="server" Text="Submit" />
</form>
</body> </html> File: web.config
<system.web>
<authentication mode="Forms"> <forms name="form1" loginUrl="Login.aspx" path="/"> <credentials passwordFormat="Clear"> <user name="userName" password="Bubbles" /> </credentials> </forms> </authentication> <authorization> <deny users="?" /> </authorization>
</system.web>
</source>
FormsAuthentication.RedirectFromLoginPage (VB)
<source lang="csharp">
<%@ Page Language="VB" %> <script runat="server">
Protected Sub Button1_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) If FormsAuthentication.Authenticate(TextBox1.Text, TextBox2.Text) Then FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, True) Else Response.Write("Invalid credentials") End If End Sub
</script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">
<title>Login Page</title>
</head> <body>
<form id="form1" runat="server">
Username
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
Password
<asp:TextBox ID="TextBox2" runat="server" TextMode="Password"></asp:TextBox>
<asp:Button ID="Button1" OnClick="Button1_Click" runat="server" Text="Submit" />
</form>
</body> </html>
File: web.config
<system.web>
<authentication mode="Forms"> <forms name="form1" loginUrl="Login.aspx" path="/"> <credentials passwordFormat="Clear"> <user name="userName" password="Bubbles" /> </credentials> </forms> </authentication> <authorization> <deny users="?" /> </authorization>
</system.web>
</source>
FormsAuthentication.SignOut()
<source lang="csharp">
<%@ Page %> <SCRIPT language="C#" runat="server">
private void Logout_Click(object sender, System.EventArgs e) { System.Web.Security.FormsAuthentication.SignOut(); Message.Text="You have been logged out."; Message.Text+="<meta http-equiv=\"Refresh\" content=\"3;URL=http://nfex.ru\" />"; }
</SCRIPT> <HTML>
<HEAD> <title>Creating a Simple Forms Authentication Logout Page</title> </HEAD> <body> <form id="form1" method="post" runat="server">
<asp:LinkButton ID="Logout" Runat="server" OnClick="Logout_Click">Logout</asp:LinkButton>
<asp:Literal ID="Message" Runat="server" />
</form> </body>
</HTML>
</source>
Hash password
<source lang="csharp">
<%@ Page Language="VB" %> <%@ Import Namespace="System.Web.Security" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Password Hashing Page</title> <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0"> <meta name="vs_targetSchema" content="http://schemas.microsoft.ru/intellisense/ie5"> <script runat="server">
Sub Hash_Click(Sender As Object, e As EventArgs) HashOut.Text = FormsAuthentication.HashPasswordForStoringInConfigFile(Password.Text, HashType.SelectedItem.Value) End Sub
</script> </head> <body>
<form runat="server">
Hash Type: |
<asp:dropdownlist id="HashType" runat="server"> <asp:listitem>MD5</asp:listitem> <asp:listitem>SHA1</asp:listitem> </asp:dropdownlist> |
Password: | <asp:textbox id="Password" textmode="Password" runat="server"/> |
<asp:button text="Hash" onclick="Hash_Click" runat="server"/> |
<asp:label id="HashOut" runat="server"/> </form>
</body> </html>
</source>
Save user account to an XML file
<source lang="csharp">
<%@ Page Language="VB" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Web.Security" %> <html> <head> <title>Registration Page</title> <script runat="server">
Sub Register_Click(Sender As Object, e As EventArgs) If Page.IsValid Then Dim LoginDS as New DataSet() LoginDS.ReadXml(Server.MapPath("Users.xml")) If LoginDS.Tables(0).Select("Email="" & Email.text & """).Length = 0 Then Dim NewUser As DataRow NewUser = LoginDS.Tables(0).NewRow() NewUser("Email") = Email.Text NewUser("Password") = FormsAuthentication.HashPasswordForStoringInConfigFile(Password.Text, "SHA1") LoginDS.Tables(0).Rows.Add(NewUser) LoginDS.WriteXml(Server.MapPath("Users.xml")) Response.Redirect(Request.QueryString("Page")) Else Message.Text = "User with email: " & Email.Text & " already exists. Please choose another email address." End If End If End Sub
</script> </head> <body>
<form runat="server">
Email: | <asp:textbox id="Email" runat="server"/> |
Desired Password: | <asp:textbox id="Password" textmode="Password" runat="server"/> |
Confirm Password: | <asp:textbox id="PasswordConfirm" textmode="Password" runat="server"/> |
<asp:button text="Submit" onclick="Register_Click" runat="server"/> | <input type="reset" value="Cancel" runat="server"/> |
<asp:comparevalidator id="comparePasswords" controltovalidate="Password" controltocompare="PasswordConfirm" display="dynamic" text="Passwords must match!" operator="Equal" runat="server"/> <asp:requiredfieldvalidator id="requireEmail" controltovalidate="Email" display="dynamic" text="Email address required!" runat="server"/> <asp:requiredfieldvalidator id="requirePassword" controltovalidate="Password" display="dynamic" text="Password required!" runat="server"/> <asp:label id="Message" runat="server"/> </form>
</body> </html> file: Users.xml <?xml version="1.0" standalone="yes"?> <Users>
<User> <Email>a@asp.ru</Email> <Password>816010E041FA485C6E2383C649343D3A0CAD4D25</Password> </User>
</Users>
</source>