Friday, September 16, 2005

How do you force a user to always login to web app?

Q: How do you force a user to always login?

A: In the Login.aspx page, the following code would be placed in the btnLogin_Click():

If wsAuth.Auth(strUID, strPWD) = True Then
'Successful Login

FormsAuthentication.SetAuthCookie(txtUserID.Text, False)
Response.Redirect("MainMenu.aspx")
Else
'Failure
ErrorLabel.Text = "Authentication did not succeed. Check user name and password."
End If



In each subsequent web page, check for authentication before loading the page. The following code would be placed in the Page_load event handler:

If Not IsPostBack Then
If Not (Request.IsAuthenticated) Then
Session.Abandon()
Response.Redirect("Login.aspx")

End If
End If


Forcing a Login and redirecting to the user's requested URL.
Q: If a user opens a browser and enters a URL to a specific page within a web application without loggin in first, how do you force him to login then redirect him to the page requested?

A: If you use the statement Response.Redirect("default.aspx?URL=" + HttpUtility.UrlEncode(Request.RawUrl)) in each page's Page_Load(), it will force users to the login page. In addition since you're passing the RawURL (the URL initially entered by the user), you can later redirect the user back to this URL only AFTER the user has logged in. This would be accomplished using the following code in the Page_Load() of each page of the application subsequent to logging in.

If Not IsPostBack Then
If Not (Request.IsAuthenticated) Then
Session.Abandon()
Response.Redirect("Login.aspx?URL=" + HttpUtility.UrlEncode(Request.RawUrl))
End If
End If


In Login.aspx, after the user has successfully logged in, we can redirect him back to the URL the user originally requested by accessing the URL passed as a parameter to the Login page.
For example, add the following code to the :

If wsAuth.Auth(strUID, strPWD) = True Then
'Successful Login
FormsAuthentication.SetAuthCookie(txtUserID.Text, False)

Response.Redirect(Request.QueryString(URL))
Else
'Failure
ErrorLabel.Text = "Authentication did not succeed. Check user name and password."
End If

No comments: