ASP.NET Tutorial/Authentication Authorization/FormsAuthentication
Содержание
- 1 Assigning a name to the user and accessing next pages
- 2 Configuring Forms Authentication
- 3 Logout
- 4 Principal Login
- 5 Set user name with FormsAuthentication.SetAuthCookie
- 6 Use the web configuration file to change the name of the authentication cookie.
- 7 Using Cookieless Forms Authentication
- 8 Using Forms Authentication Across Domains: Query String Authenticate
- 9 Using Sliding Expiration with Forms Authentication
- 10 Validate a user with FormsAuthentication.Authenticate
- 11 Web configuration file contains a list of usernames and passwords.
Assigning a name to the user and accessing next pages
<source lang="csharp">
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.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: Default.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) { this.SetFocus("userName"); } protected void LogonUser(object sender, EventArgs e) { bool bAuthenticated = false; string user = userName.Text; string pswd = passWord.Text; 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) { return true; }
}</source>
Configuring Forms Authentication
<source lang="csharp">
Several configuration options are specific to Forms authentication: cookieless: Use Forms authentication when a browser does not support cookies.
Possible values are UseCookies, UseUri, AutoDetect, and UseDeviceProfile. The default value is UseDeviceProfile.
defaultUrl: Set the redirected page after being authenticated.
The default value is Default.aspx.
domain: Domain associated with the authentication cookie.
The default value is an empty string.
enableCrossAppRedirects: authenticate users across applications by passing an authentication ticket in a query string.
The default value is false.
loginUrl: Set the path to the Login page.
The default value is Login.aspx.
name: specify the name of the authentication cookie.
The default value is .ASPXAUTH.
path: Set the path associated with the authentication cookie.
The default value is /.
protection: Set how the authentication cookie is encrypted.
Possible values are All, Encryption, None, and Validation. The default value is All.
requiresSSL: Require a SSL (Secure Sockets Layer) connection when transmitting the authentication cookie.
The default value is false.
slidingExpiration: Prevent the authentication cookie from expiring as long as a user continues to make requests within an interval of time.
Possible values are True and False. The default value is True.
timeout: Set the amount of time in minutes before the authentication cookie expires.
The default value is 30.</source>
Logout
<source lang="csharp">
<%@ Page Language="VB" %> <%@ Import Namespace="System.Web.Security" %> <html> <head> <title>Logout Page</title> <script runat="server">
Sub Page_Load(Sender As Object, e As EventArgs) FormsAuthentication.SignOut() Message.Text = "You have been logged out." End Sub
</script> </head> <body>
<asp:label id="Message" runat="server"/>
</body> </html></source>
Principal Login
<source lang="csharp">
<%@Page language="C#" %> <script runat="server"> protected void Page_Load(object o, EventArgs e) {
if(IsPostBack) { if(AuthenticateUser(username.Text, password.Text)) { FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, username.Text, DateTime.Now, DateTime.Now.AddMinutes(30), false, "superusers" ); string encryptedTicket = FormsAuthentication.Encrypt(ticket); Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)); Response.Redirect(FormsAuthentication.GetRedirectUrl(username.Text, false)); } else { instructions.Text = "Please Try Again!"; instructions.ForeColor = System.Drawing.Color.Red; } }
} bool AuthenticateUser(string username, string password) {
if((username == "TheUsername") && (password == "ThePassword")) { return true; } return false;
}
</script>
<form runat="server">
<asp:Label runat="server" id="instructions" Text="Please Input your credentials" />
Username: <asp:Textbox runat="server" id="username" />
Password: <asp:Textbox runat="server" id="password" TextMode="Password" />
<asp:button runat="server" Text="LOGIN" />
</form></source>
Set user name with FormsAuthentication.SetAuthCookie
<source lang="csharp">
<%@ Page Language="VB" %> <script runat="server">
sub Login(Sender as Object, e as EventArgs) if tbUserName.Text = "user" and _ tbPassword.Text = "pass" then FormsAuthentication.SetAuthCookie(tbUserName.Text, false) Response.redirect("http://www.nfex.ru") else lblMessage.Text = "Sorry, " & _ "invalid username or password!" end if end sub
</script> <html><body>
Please enter your username and password. <form runat="server"> <asp:Label id="lblMessage" runat="server" /> Username: <asp:Textbox id="tbUserName" runat="server" />
Password: <asp:Textbox id="tbPassword" TextMode="password" runat="server" /> <asp:Button id="Submit" runat="server" OnClick="Login" Text="Submit" /> </form>
</body></html></source>
Use the web configuration file to change the name of the authentication cookie.
<source lang="csharp">
File: Web.Config <configuration>
<system.web> <authentication mode="Forms"> <forms name="MyApp" /> </authentication> </system.web>
</configuration></source>
Using Cookieless Forms Authentication
<source lang="csharp">
When cookieless authentication is enabled, a user can be identified by a unique token added to a page"s URL.
The following web configuration file enables AutoDetect. File: Web.Config <configuration>
<system.web> <authentication mode="Forms"> <forms cookieless="AutoDetect"/> </authentication> </system.web>
</configuration></source>
Using Forms Authentication Across Domains: Query String Authenticate
<source lang="csharp">
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server">
void Page_Load() { string cookieName = FormsAuthentication.FormsCookieName; string cookieValue = FormsAuthentication.GetAuthCookie(User.Identity.Name, false).Value; lnkOtherDomain.NavigateUrl += String.Format("?{0}={1}", cookieName, cookieValue); }
</script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">
<title>Query String Authenticate</title>
</head> <body>
<form id="form1" runat="server">
<asp:HyperLink id="lnkOtherDomain" Text="Link to Other Domain" NavigateUrl="http://www.nfex.ru" Runat="server" />
</form>
</body> </html> </html></source>
Using Sliding Expiration with Forms Authentication
<source lang="csharp">
Forms authentication uses a sliding expiration policy. As long as a user lets no more than 30 minutes pass without requesting a page, the user continues to be authenticated. However, if the user does not request a page for 30 minutes, then the user is logged out automatically. The following web configuration file forces a user to log in again every minute. File: Web.Config <configuration>
<system.web> <authentication mode="Forms"> <forms slidingExpiration="false" timeout="1" /> </authentication> </system.web>
</configuration></source>
Validate a user with FormsAuthentication.Authenticate
<source lang="csharp">
<%@ Page Language="VB" %> <script runat="server">
sub Login(Sender as Object, e as EventArgs) if FormsAuthentication.Authenticate(tbUserName.Text,tbPassword.Text) then FormsAuthentication.SetAuthCookie(tbUsername.Text, false) lblMessage.Text = "Success!" else lblMessage.Text = "Sorry, " & _ "invalid username or password!" end if end sub
</script> <html><body>
Please enter your username and password. <form runat="server"> <asp:Label id="lblMessage" runat="server" /> Username: <asp:Textbox id="tbUserName" runat="server" />
Password: <asp:Textbox id="tbPassword" TextMode="password" runat="server" /> <asp:Button id="Submit" runat="server" OnClick="Login" Text="Submit" /> </form>
</body></html></source>
Web configuration file contains a list of usernames and passwords.
<source lang="csharp">
File: Web.Config <configuration>
<system.web> <authentication mode="Forms"> <forms> <credentials passwordFormat="Clear"> <user name="Bill" password="secret" /> <user name="Jane" password="secret" /> <user name="Fred" password="secret" /> </credentials> </forms> </authentication> </system.web>
</configuration>
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server">
protected void btnLogin_Click(object sender, EventArgs e) { if (FormsAuthentication.Authenticate(txtUserName.Text,txtPassword.Text)) FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, chkRememberMe.Checked); else lblError.Text = "Invalid user name/password"; }
</script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">
<title>Forms Login</title>
</head> <body>
<form id="form1" runat="server">
<asp:Label id="lblError" EnableViewState="false" ForeColor="Red" Runat="server" />
<asp:Label id="lblUserName" Text="User Name:" AssociatedControlID="txtUserName" Runat="server" />
<asp:TextBox id="txtUserName" Runat="server" />
<asp:Label id="lblPassword" Text="Password:" AssociatedControlID="txtPassword" Runat="server" />
<asp:TextBox id="txtPassword" TextMode="Password" Runat="server" />
<asp:CheckBox id="chkRememberMe" Text="Remember Me" Runat="server" />
<asp:Button id="btnLogin" Text="Login" OnClick="btnLogin_Click" Runat="server" />
</form>
</body> </html></source>