Forms Authentication - Redirect Page and http to https problem

A worthy article by  Harish Ranganathan about FormsAuthentication, my experience on this is when we didn't use RedirectFromLoginPage to navigate, must call SetAuthcookie() to authenticate our privilege. After that, just use ourself navigation. Some variable in Require.ServerVariables are useful for this purpose.

If Request.ServerVariables("SERVER_PORT")=80 Then 'If Request.ServerVariables("HTTPS")= "on"
      Dim strSecureURL
      strSecureURL = "https://"
      strSecureURL = strSecureURL & Request.ServerVariables("SERVER_NAME")
      strSecureURL = strSecureURL & Request.ServerVariables("URL")
      Response.Redirect strSecureURL
   End If

----

In this article I will explain how to redirect users to a specific page rather than the generic default.aspx upon successful authentication of the user.

While using ASP.NET Forms authentication, if we try to access a protected page, the user would be taken to the login.aspx page with the ReturnUrl parameter having the path for the originally requested page.

Once, the user's credentials are verified, the RedirectFromLoginPage method can be used to take the user back to the originally requested page.

However, if there is no specified ReturnUrl, then FormsAuthentication by default takes the user to the default.aspx page upon successful authentication.

If we do not have a default.aspx page or we want to take the users to our custom page etc., then we can use the Setauthcookie method to set the cookie and then redirect users to our desired page. The following code establishes the same.

// Once the user's entered credentials are verified //
if(Request.Params["ReturnUrl"] != null)
{
FormsAuthentication.RedirectFromLoginPage(txtUserName.text, false);
}
else
{
FormsAuthentication.SetAuthcookie(txtUserName.text, false);
Response.Redirect("CustomPage.aspx");
}

The above code first verifies whether there is any ReturnUrl parameter such that if exists, it should take to the originally requested page.

Else, it sets the authcookie and then redirects user to a custom page.

The txtUserName is the ID of the textbox which is used to capture the username.

This article applies to ASP.NET 1.0 & 1.1 Versions.
 
Harish Ranganathan

0 nhận xét:

 

Coding experience share Copyright © 2010 | Designed by Ipietoon for Free Blogger Template