Redirect user to requested page after successful authentication in VB.NET

In this article we are going to see when a user requests a webpage and if the page is accessible only to authenticated users and when the user is redirected to login page, then in the login page after successful authentication how we can redirect the user back to the same requested page.

If the Requirement is to redirect the user back to requested page after successful authentication in VB.NET. Please follow below steps:

1. Open a New VB.NET website.
2. In the web.config file of the website, mention the login url in the Forms tag of authentication section as shown below:

<authentication mode="Forms" >
<forms loginUrl="Login.aspx" timeout="2880"/>

loginUrl is the url of the page to which user is redirected for authentication, if the user is not logged into the web application. So whenever user requests a page which needs authentication that is if the user has to be authenticated to access the webpage, then user is redirected to Login.aspx page.

3.Let us assume that user is trying to access Default.aspx page which needs authentication. Then write the below code to check if the user is authenticated or not. It redirects the user to Login.aspx page if the user is not authenticated.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Request.IsAuthenticated Then
End If
End Sub

As you can see in the below image, the querystring with name "ReturnUrl" has the url of the page which is originally been requested.

Default page url if not authenticated

4. In the Login.aspx.cs file, write the below code to authenticate the user from the database by checking the valid userid and password and if it is present in the database, then user is considered as authenticated and redirect the user back to the originally requested page or the default page.

Dim uid As String = txtUserId.Text
Dim pwd As String = txtPassword.Text
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("EmpDB").ConnectionString)
Dim cmd As New SqlCommand("UserDetails", con)
cmd.CommandType = Data.CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@userid", uid)
cmd.Parameters.AddWithValue("@password", pwd)
Dim rdr As SqlDataReader
rdr = cmd.ExecuteReader()
If rdr.HasRows() = True Then
'If user information is present in database.
While (rdr.Read())
'Redirect the user to requested page.
FormsAuthentication.RedirectFromLoginPage(uid, True)
End While
End If
Catch ex As Exception
End Try

Note: You can also get the access to the initially requested page by the user using the following code:

dim returnUrl as string = Request.QueryString("ReturnUrl")


No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: