ASP.NET Tutorial/Authentication Authorization/FormsAuthentication

Материал из .Net Framework эксперт
Версия от 11:57, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Assigning a name to the user and accessing next pages

<%@ 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>
  <b style="color:red;"><asp:label runat="server" id="errorMsg"/></b>
  <br /><br />
  
  <div id="pageContent">
      <form id="Form1" runat="server">
        <table>
        <tr>
          <td><b>User ID</b></td>
          <td><asp:textbox runat="server" text="" id="userName" /></td></tr>
        <tr>
          <td><b>Password</b></td>
          <td><asp:textbox runat="server" text="" id="passWord" textmode="password" /></td></tr>
        </table>
        <asp:button ID="Button1" runat="server" text="Log In..." onclick="LogonUser" />
      </form>
  </div>
</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;
    }
}


Configuring Forms Authentication

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.


Logout

<%@ 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>


Principal Login

<%@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" /><br> 
Username: <asp:Textbox runat="server" id="username" /><br>
Password: <asp:Textbox runat="server" id="password" TextMode="Password" /><br>
<asp:button runat="server" Text="LOGIN" />
</form>


Set user name with FormsAuthentication.SetAuthCookie

<%@ 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 = "<font color=red>Sorry, " & _
            "invalid username or password!</font>"
      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" /><br>
      Password:
      <asp:Textbox id="tbPassword" TextMode="password"
         runat="server" />
      <asp:Button id="Submit" runat="server"
         OnClick="Login"
         Text="Submit" />
   </form>
</body></html>


Use the web configuration file to change the name of the authentication cookie.

File: Web.Config
<configuration>
    <system.web>
      <authentication mode="Forms">
        <forms name="MyApp" />
      </authentication>
    </system.web>
</configuration>


Using Cookieless Forms Authentication

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>


Using Forms Authentication Across Domains: Query String Authenticate

<%@ 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">
    <div>
    <asp:HyperLink
        id="lnkOtherDomain"
        Text="Link to Other Domain"
        NavigateUrl="http://www.nfex.ru"
        Runat="server" />
    </div>
    </form>
</body>
</html>
</html>


Using Sliding Expiration with Forms Authentication

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>


Validate a user with FormsAuthentication.Authenticate

<%@ 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 = "<font color=red>Success!</font>"
      else
         lblMessage.Text = "<font color=red>Sorry, " & _
            "invalid username or password!</font>"
      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" /><br>
    Password:
    <asp:Textbox id="tbPassword" TextMode="password" 
       runat="server" />
    <asp:Button id="Submit" runat="server" 
       OnClick="Login" 
       Text="Submit" />
   </form>
</body></html>


Web configuration file contains a list of usernames and passwords.

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">
    <div>
    <asp:Label
        id="lblError"
        EnableViewState="false"
        ForeColor="Red"
        Runat="server" />
    <br /><br />
    <asp:Label
        id="lblUserName"
        Text="User Name:"
        AssociatedControlID="txtUserName"
        Runat="server" />
    <br />
    <asp:TextBox
        id="txtUserName"
        Runat="server" />
    <br /><br />
    <asp:Label
        id="lblPassword"
        Text="Password:"
        AssociatedControlID="txtPassword"
        Runat="server" />
    <br />
    <asp:TextBox
        id="txtPassword"
        TextMode="Password"
        Runat="server" />
    <br /><br />
    <asp:CheckBox
        id="chkRememberMe"
        Text="Remember Me"
        Runat="server" />
    <br /><br />
    <asp:Button
        id="btnLogin"
        Text="Login"
        OnClick="btnLogin_Click"
        Runat="server" />
    </div>
    </form>
</body>
</html>