Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
.NET Framework 3.5
 RedirectFromLoginPage Method (Strin...

  Switch on low bandwidth view
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
.NET Framework Class Library
FormsAuthentication..::.RedirectFromLoginPage Method (String, Boolean)

Redirects an authenticated user back to the originally requested URL or the default URL.

Namespace:  System.Web.Security
Assembly:  System.Web (in System.Web.dll)
Visual Basic (Declaration)
Public Shared Sub RedirectFromLoginPage ( _
    userName As String, _
    createPersistentCookie As Boolean _
)
Visual Basic (Usage)
Dim userName As String
Dim createPersistentCookie As Boolean

FormsAuthentication.RedirectFromLoginPage(userName, _
    createPersistentCookie)
C#
public static void RedirectFromLoginPage(
    string userName,
    bool createPersistentCookie
)
Visual C++
public:
static void RedirectFromLoginPage(
    String^ userName, 
    bool createPersistentCookie
)
JScript
public static function RedirectFromLoginPage(
    userName : String, 
    createPersistentCookie : boolean
)

Parameters

userName
Type: System..::.String
The authenticated user name.
createPersistentCookie
Type: System..::.Boolean
true to create a durable cookie (one that is saved across browser sessions); otherwise, false.
ExceptionCondition
HttpException

The return URL specified in the query string contains a protocol other than HTTP: or HTTPS:.

The RedirectFromLoginPage method redirects to the URL specified in the query string using the ReturnURL variable name. For example, in the URL http://www.contoso.com/login.aspx?ReturnUrl=caller.aspx, the RedirectFromLoginPage method redirects tothe return URL caller.aspx. If the ReturnURL variable does not exist, the RedirectFromLoginPage method redirects to the URL in the DefaultUrl property.

ASP.NET automatically adds the return URL when the browser is redirected to the login page.

By default, the ReturnUrl variable must refer to a page within the current application. If ReturnUrl refers to a page in a different application or on a different server, the RedirectFromLoginPage methods redirects to the URL in the DefaultUrl property. If you want to allow redirects to a page outside the current application, you must set the EnableCrossAppRedirects property to true using the enableCrossAppRedirects attribute of the forms configuration element.

Security noteSecurity Note:

Setting the EnableCrossAppRedirects property to true to allow cross-application redirects is a potential security threat. When cross-application redirects are allowed, your site is vulnerable to malicious Web sites that use your login page to convince your Web site users that they are using a secure page on your site. To improve security when using cross-application redirects, you should override the RedirectFromLoginPage method to allow redirects only to approved Web sites.

If the CookiesSupported property is true, and either the ReturnUrl variable is within the current application or the EnableCrossAppRedirects property is true, then the RedirectFromLoginPage method issues an authentication ticket and places it in the default cookie using the SetAuthCookie method.

If CookiesSupported is false and the redirect path is to a URL in the current application, the ticket is issued as part of the redirect URL. If CookiesSupported is false, EnableCrossAppRedirects is true, and the redirect URL does not refer to a page within the current application, the RedirectFromLoginPage method issues an authentication ticket and places it in the QueryString property.

The following code example redirects validated users to either the originally requested URL or the DefaultUrl. The code example uses ASP.NET membership to validate users. For more information about ASP.NET membership, see Managing Users by Using Membership.

Security noteSecurity Note:

This example contains a text box that accepts user input, which is a potential security threat. By default, ASP.NET Web pages validate that user input does not include script or HTML elements. For more information, see Script Exploits Overview.

Visual Basic
<%@ Page Language="VB" %>
<%@ Import Namespace="System.Web.Security" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

Public Sub Login_OnClick(sender As Object, args As  EventArgs)

   If (Membership.ValidateUser(UsernameTextbox.Text, PasswordTextbox.Text)) Then
      FormsAuthentication.RedirectFromLoginPage(UsernameTextbox.Text, NotPublicCheckBox.Checked)
   Else
     Msg.Text = "Login failed. Please check your user name and password and try again."
   End If

End Sub

</script>

<html  >
<head>
  <title>Login</title>
</head>
<body>

<form id="form1" runat="server">
  <h3>Login</h3>

  <asp:Label id="Msg" ForeColor="maroon" runat="server" /><br />

  Username: <asp:Textbox id="UsernameTextbox" runat="server" /><br />
  Password: <asp:Textbox id="PasswordTextbox" runat="server" TextMode="Password" /><br />

  <asp:Button id="LoginButton" Text="Login" OnClick="Login_OnClick" runat="server" />
  <asp:CheckBox id="NotPublicCheckBox" runat="server" /> 
  Check here if this is <span style="text-decoration:underline">not</span> a public computer.

</form>

</body>
</html>

C#
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Security" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

public void Login_OnClick(object sender, EventArgs args)
{
   if (Membership.ValidateUser(UsernameTextbox.Text, PasswordTextbox.Text))
      FormsAuthentication.RedirectFromLoginPage(UsernameTextbox.Text, NotPublicCheckBox.Checked);
   else
     Msg.Text = "Login failed. Please check your user name and password and try again.";
}


</script>

<html  >
<head>
  <title>Login</title>
</head>
<body>

<form id="form1" runat="server">
  <h3>Login</h3>

  <asp:Label id="Msg" ForeColor="maroon" runat="server" /><br />

  Username: <asp:Textbox id="UsernameTextbox" runat="server" /><br />
  Password: <asp:Textbox id="PasswordTextbox" runat="server" TextMode="Password" /><br />

  <asp:Button id="LoginButton" Text="Login" OnClick="Login_OnClick" runat="server" />
  <asp:CheckBox id="NotPublicCheckBox" runat="server" /> 
  Check here if this is <span style="text-decoration:underline">not</span> a public computer.

</form>

</body>
</html>

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0
Tags What's this?: c# (x) Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
other example by Sameer Talar      nortonorozco dat com ... Red-Devile   |   Edit   |   Show History
As you have probably deduced, forms authentication requires a form. Add a second web form, Login.aspx, to the project. For now, just place a single button, btnAuthenticate, on the form. Add a using statement for System.Web.Security at the top of the form's module, and then the code for this button to call::


private void btnAuthenticate_Click(object sender, System.EventArgs e)
{
FormsAuthentication.RedirectFromLoginPage("Mike", false);
}
You'll also need to make some changes to the Web.config file to tell ASP.NET to use forms authentication with this particular application. First, replace the existing authentication section:


<authentication mode="Forms">
<forms name="SampleAuth"
loginUrl="Login.aspx"
slidingExpiration="true">
</forms>
</authentication>
That configuration section tells ASP.NET to use forms authentication, and to create a cookie named SampleAuth to store information on the user's computer. The loginUrl attribute indicates the form that should be used for authentication, and the slidingExpiration attribute resets the expiration time of the cookie each time the application gets a request from the user (by default, sessions expire in 30 minutes).

You'll also need to modify the authorization section of the Web.config file:


<authorization>
<deny users="?" />
</authorization>
By default, the authorization section in the Web.config file allows all users access to the entire application. With this change, it explicitly denies access for unauthenticated users.

Run the application again, and instead of Default.aspx, you'll see Login.aspx. Click the button, and the application will redirect you back to Default.aspx, where the label will show the name of the authenticated user. The sequence of events goes like this:

The user requests Default.aspx.
ASP.NET notes that the application uses forms authentication and that the user has not yet been authenticated, so it redirects to Login.aspx.
When the user clicks the button, the code uses the FormsAuthentication.RedirectFromLoginPage method. This method announces to ASP.NET that you're satisfied with this user's credentials. The first parameter to the method is the name to assign to the user, and the second is a Boolean value that indicates whether a permanent cookie should be saved on the user's hard drive.
ASP.NET knows that the user was originally trying to load Default.aspx, so that's the page that it redirects to, in this case.
The identity of the now-authenticated user is available to any code that needs it.
Some of the Fiddly Bits
You can control the behavior of the forms authentication engine somewhat by the attributes that you supply for the <forms> element in the Web.config file. Here are the attributes that you can use for this element:

Attribute Purpose
loginUrl Name of the web form to send all unauthenticated requests to. This defaults to Default.aspx.
name Name of the cookie to use to store the authenticated identity. This defaults to .ASPXAUTH. If there are multiple applications on your server using forms authentication, and you leave this set to the default, then they'll all share the same cookie. That's a problem if they don't all have the same authentication requirements. I recommend always setting this to a unique value for each application.
path Path where the cookie will be stored. Defaults to a single slash.
protection Specifies the verification method to use to prevent cookie spoofing: None, Encryption (encrypts but doesn't validate the cookie), Validation (adds a validation key to the cookie), and All (the default, which both encrypts and validates the cookie). Unless your web server is extremely overloaded, leave this at the default value of All.
requiresSSL A Boolean value that determines whether ASP.NET demands an SSL connection for the cookie. The default is false.
slidingExpiration Specifies whether the cookie times out at a fixed point after the initial authentication (false, which is the default), or whether the timeout is reset with each request (true).
timeout The number of minutes it takes for the cookie to expire. The default is 30. For permanent cookies, this attribute is ignored.

A Little More Realism, Please
So far, my forms-based authentication isn't really doing much authenticating; anyone who can click a button has access to the entire application. It's up to you to decide just how you want to authenticate users of your application, and to supply custom code to fit your scheme. A typical scheme might require users to type in a username and a password on the login page. To support this, add two TextBox controls, txtUsername and txtPassword, to the Login.aspx page. Now you can alter the code to distinguish between different users:


void btnAuthenticate_Click(object sender, EventArgs e) {
if(txtUserName.Text == "Mike" &&
txtPassword.Text == "Soup") {
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text,
false);
}

if(txtUserName.Text == "Adam" &&
txtPassword.Text == "Dinosaur") {
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text,
false);
}
}
Now you'll find that if you submit a proper combination of username and password, you still end up on Default.aspx, and it knows which user you logged in as. If you submit an invalid combination, the call to FormsAuthentication.RedirectFromLoginPage will never happen, and the browser will just reload Login.aspx. Of course, hard-wiring usernames and passwords directly into your source code is a pretty horrible idea; it means you have to modify the source code every time your user list changes. In a real application, you'd typically check against a database or XML file of users, which can be modified more easily at runtime. But the authentication engine doesn't care; you can use whatever scheme you like to decide whether users are legitimate.
Tags What's this?: c# (x) Add a tag
Flag as ContentBug
other example      nortonorozco dat com   |   Edit   |   Show History

As you have probably deduced, forms authentication requires a form. Add a second web form, Login.aspx, to the project. For now, just place a single button, btnAuthenticate, on the form. Add a using statement for System.Web.Security at the top of the form's module, and then the code for this button to call:


private void btnAuthenticate_Click(object sender, System.EventArgs e)
{
FormsAuthentication.RedirectFromLoginPage("Mike", false);
}
You'll also need to make some changes to the Web.config file to tell ASP.NET to use forms authentication with this particular application. First, replace the existing authentication section:


<authentication mode="Forms">
<forms name="SampleAuth"
loginUrl="Login.aspx"
slidingExpiration="true">
</forms>
</authentication>
That configuration section tells ASP.NET to use forms authentication, and to create a cookie named SampleAuth to store information on the user's computer. The loginUrl attribute indicates the form that should be used for authentication, and the slidingExpiration attribute resets the expiration time of the cookie each time the application gets a request from the user (by default, sessions expire in 30 minutes).

You'll also need to modify the authorization section of the Web.config file:


<authorization>
<deny users="?" />
</authorization>
By default, the authorization section in the Web.config file allows all users access to the entire application. With this change, it explicitly denies access for unauthenticated users.

Run the application again, and instead of Default.aspx, you'll see Login.aspx. Click the button, and the application will redirect you back to Default.aspx, where the label will show the name of the authenticated user. The sequence of events goes like this:

The user requests Default.aspx.
ASP.NET notes that the application uses forms authentication and that the user has not yet been authenticated, so it redirects to Login.aspx.
When the user clicks the button, the code uses the FormsAuthentication.RedirectFromLoginPage method. This method announces to ASP.NET that you're satisfied with this user's credentials. The first parameter to the method is the name to assign to the user, and the second is a Boolean value that indicates whether a permanent cookie should be saved on the user's hard drive.
ASP.NET knows that the user was originally trying to load Default.aspx, so that's the page that it redirects to, in this case.
The identity of the now-authenticated user is available to any code that needs it.
Some of the Fiddly Bits
You can control the behavior of the forms authentication engine somewhat by the attributes that you supply for the <forms> element in the Web.config file. Here are the attributes that you can use for this element:

Attribute Purpose
loginUrl Name of the web form to send all unauthenticated requests to. This defaults to Default.aspx.
name Name of the cookie to use to store the authenticated identity. This defaults to .ASPXAUTH. If there are multiple applications on your server using forms authentication, and you leave this set to the default, then they'll all share the same cookie. That's a problem if they don't all have the same authentication requirements. I recommend always setting this to a unique value for each application.
path Path where the cookie will be stored. Defaults to a single slash.
protection Specifies the verification method to use to prevent cookie spoofing: None, Encryption (encrypts but doesn't validate the cookie), Validation (adds a validation key to the cookie), and All (the default, which both encrypts and validates the cookie). Unless your web server is extremely overloaded, leave this at the default value of All.
requiresSSL A Boolean value that determines whether ASP.NET demands an SSL connection for the cookie. The default is false.
slidingExpiration Specifies whether the cookie times out at a fixed point after the initial authentication (false, which is the default), or whether the timeout is reset with each request (true).
timeout The number of minutes it takes for the cookie to expire. The default is 30. For permanent cookies, this attribute is ignored.

A Little More Realism, Please
So far, my forms-based authentication isn't really doing much authenticating; anyone who can click a button has access to the entire application. It's up to you to decide just how you want to authenticate users of your application, and to supply custom code to fit your scheme. A typical scheme might require users to type in a username and a password on the login page. To support this, add two TextBox controls, txtUsername and txtPassword, to the Login.aspx page. Now you can alter the code to distinguish between different users:


void btnAuthenticate_Click(object sender, EventArgs e) {
if(txtUserName.Text == "Mike" &&
txtPassword.Text == "Soup") {
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text,
false);
}

if(txtUserName.Text == "Adam" &&
txtPassword.Text == "Dinosaur") {
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text,
false);
}
}
Now you'll find that if you submit a proper combination of username and password, you still end up on Default.aspx, and it knows which user you logged in as. If you submit an invalid combination, the call to FormsAuthentication.RedirectFromLoginPage will never happen, and the browser will just reload Login.aspx. Of course, hard-wiring usernames and passwords directly into your source code is a pretty horrible idea; it means you have to modify the source code every time your user list changes. In a real application, you'd typically check against a database or XML file of users, which can be modified more easily at runtime. But the authentication engine doesn't care; you can use whatever scheme you like to decide whether users are legitimate.


Tags What's this?: c# (x) Add a tag
Flag as ContentBug
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker