Hi ramco1917,
using the following article i have created the example.
Please refer it and modify as per your requirement.
Implement Role based security using Forms Authentication in ASP.Net
HTML
Login
<asp:Login ID="Login1" runat="server" OnAuthenticate="ValidateUser"></asp:Login>
Home
<div>
Welcome
<asp:LoginName ID="LoginName1" runat="server" Font-Bold="true" />
<br /><br />
<asp:LoginStatus ID="LoginStatus1" runat="server" />
</div>
Namespaces
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Security;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.Security
Code
Login
C#
protected void ValidateUser(object sender, EventArgs e)
{
int userId = 0;
string roles = string.Empty;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Validate_User"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Username", Login1.UserName);
cmd.Parameters.AddWithValue("@Password", Login1.Password);
cmd.Connection = con;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
userId = Convert.ToInt32(reader["UserId"]);
roles = reader["Roles"].ToString();
con.Close();
}
switch (userId)
{
case -1:
Login1.FailureText = "Username and/or password is incorrect.";
break;
case -2:
Login1.FailureText = "Account has not been activated.";
break;
default:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, Login1.UserName, DateTime.Now, DateTime.Now.AddMinutes(2880), Login1.RememberMeSet, roles, FormsAuthentication.FormsCookiePath);
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
if (ticket.IsPersistent)
{
cookie.Expires = ticket.Expiration;
}
Response.Cookies.Add(cookie);
Response.Redirect(FormsAuthentication.GetRedirectUrl(Login1.UserName, Login1.RememberMeSet));
break;
}
}
}
VB.Net
Protected Sub ValidateUser(sender As Object, e As EventArgs)
Dim userId As Integer = 0
Dim roles As String = String.Empty
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("Validate_User")
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@Username", Login1.UserName)
cmd.Parameters.AddWithValue("@Password", Login1.Password)
cmd.Connection = con
con.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
reader.Read()
userId = Convert.ToInt32(reader("UserId"))
roles = reader("Roles").ToString()
con.Close()
End Using
Select Case userId
Case -1
Login1.FailureText = "Username and/or password is incorrect."
Exit Select
Case -2
Login1.FailureText = "Account has not been activated."
Exit Select
Case Else
Dim ticket As New FormsAuthenticationTicket(1, Login1.UserName, DateTime.Now, DateTime.Now.AddMinutes(2880), Login1.RememberMeSet, roles,
FormsAuthentication.FormsCookiePath)
Dim hash As String = FormsAuthentication.Encrypt(ticket)
Dim cookie As New HttpCookie(FormsAuthentication.FormsCookieName, hash)
If ticket.IsPersistent Then
cookie.Expires = ticket.Expiration
End If
Response.Cookies.Add(cookie)
Response.Redirect(FormsAuthentication.GetRedirectUrl(Login1.UserName, Login1.RememberMeSet))
Exit Select
End Select
End Using
End Sub
Home
C#
protected void Page_Load(object sender, EventArgs e)
{
Tuple<bool, string, string> authenticatedUser = this.AuthenticatedUser();
if (authenticatedUser.Item1) // Check if the user is authenticated
{
string userRole = authenticatedUser.Item2;
string loginId = authenticatedUser.Item3;
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('Role: " + userRole + "\\nId: " + loginId + "');", true);
}
}
public Tuple<bool, string, string> AuthenticatedUser()
{
try
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
return Tuple.Create(true, ticket.UserData, HttpContext.Current.User.Identity.Name);
}
else
{
FormsAuthentication.RedirectToLoginPage();
return Tuple.Create(false, string.Empty, string.Empty);
}
}
catch (Exception ex)
{
FormsAuthentication.RedirectToLoginPage();
return Tuple.Create(false, string.Empty, string.Empty);
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim authenticatedUser As Tuple(Of Boolean, String, String) = Me.AuthenticatedUser()
If authenticatedUser.Item1 Then ' Check if the user is authenticated
Dim userRole As String = authenticatedUser.Item2
Dim loginId As String = authenticatedUser.Item3
ClientScript.RegisterClientScriptBlock(Me.GetType(), "alert", "alert('Role: " & userRole & "\nId: " & loginId & "');", True)
End If
End Sub
Public Function AuthenticatedUser() As Tuple(Of Boolean, String, String)
Try
If HttpContext.Current.User.Identity.IsAuthenticated Then
Dim id As FormsIdentity = CType(HttpContext.Current.User.Identity, FormsIdentity)
Dim ticket As FormsAuthenticationTicket = id.Ticket
Return Tuple.Create(True, ticket.UserData, HttpContext.Current.User.Identity.Name)
Else
FormsAuthentication.RedirectToLoginPage()
Return Tuple.Create(False, String.Empty, String.Empty)
End If
Catch ex As Exception
FormsAuthentication.RedirectToLoginPage()
Return Tuple.Create(False, String.Empty, String.Empty)
End Try
End Function
Screenshot