Constructing Login Form
Construct a login form that has textbox for entering
userid and password, a button for login with an optional Remember me checkbox.
Refer below figure.
On Login button click do the following steps,
1. Create Forms Authentication
ticket,
Listing 1 – FormsAuthentication ticket syntax
FormsAuthenticationTicket ticket = new
FormsAuthenticationTicket(
int version,
string
userName,
DateTime
CreationTime,
DateTime Expiration,
bool IsPersistent,
string UserData,
string CookiePath);
User’s role information can be specified in UserData in
the above argument list.
2. Encrypt the above created
ticket through following method in FormsAuthentication class,
Listing 2 - Encrypt Ticket
string Encrypt(FormsAuthenticationTicket ticket);
It returns a string containing an encrypted
forms-authentication ticket suitable for use in an HTTP cookie.
1. Create the cookie with the
encrypted.
2. Add the created cookie to the
response object.
The below code Listing 3 shows the implementation of the
above steps.
Listing 3 - Login Event
protected void btnLogin_Click(object sender, EventArgs
e)
{
User _user = new User();
DBOperations dbo = new DBOperations();
_user = dbo.CheckUser(txtUserid.Text);
if (_user != null)
{
if (_user.Password == txtPassword.Text)
{
FormsAuthenticationTicket Authticket =
new
FormsAuthenticationTicket(1,
txtUserid.Text,
DateTime.Now,
DateTime.Now.AddMinutes(30),
chkRememberMe.Checked,
_user.Role,
FormsAuthentication.FormsCookiePath);
string hash = FormsAuthentication.
Encrypt(Authticket);
HttpCookie Authcookie = new HttpCookie(
FormsAuthentication.FormsCookieName,hash);
if (Authticket.IsPersistent)
Authcookie.Expires =
Authticket.Expiration;
Response.Cookies.Add(Authcookie);
string returnUrl =
Request.QueryString["ReturnUrl"];
if (returnUrl == null)
returnUrl = "/";
Response.Redirect(returnUrl);
}
else
{
lblMessage.Text = "Password does'nt
match.";
}
}
else
{
lblMessage.Text = "User not exists.";
}
}
Since the user information is stored as encrypted value
in the cookie we need to construct the decrypted version of our credentials for
every request and assign it to the Context object. This is done to make the user
information available on the pages. The FormsAuthentication module will decrypt
the forms authentication ticket in the cookie and make it available through the
property HttpContext.Current.User.Identity. A new GenericPrincipal object should
be constructed and assigned to the User property of Context object. This has to
be done in Application_AuthenticateRequest event in Global.asax file. By
default, there will be no Global.asax file added to our solution if you use
visual studio 2005 so we need to add it explicitly through “Add new Item”.
Listing 4 - Application Authenticate Event
protected void Application_AuthenticateRequest(Object
sender,EventArgs e)
{
if (HttpContext.Current.User != null)
{
if
(HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity
is FormsIdentity)
{
FormsIdentity id =
(FormsIdentity)
HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket =
id.Ticket;
string userInfo =
ticket.UserData;
string[] roles =
userInfo.Split(',');
HttpContext.Current.User =
new GenericPrincipal(id,
roles);
}
}
}
}
We need to import System.Security.Principal namespace to
the Global.asax file for the above code to work. Refer the below snippet.
Listing 5 - Import Namespace
<%@ Import Namespace="System.Security.Principal"
%>
Checking User Role in Code
The following code snippet will help us to check if the
logged in user is part of a role.
Listing 6 - Role Chech In Code
if (User.IsInRole("ADMIN"))
lblMessage.Text = TechnicalErrorMsg;
Refer the link in Reference section of this article to
deal with some of the common problems we may face when implementing forms
authentication with roles.
How to use the source code attached with this
article?
Unzip code, open it with visual studio 2005 and hit F5
to run. The code uses database attached in APP_Data, so you need to change any
setting in Web.Config. The database has already 2 user ids created, test1 for
ADMIN role and test2 for Publisher role, passwords are same as userid. Download
the code and understand it better.
Download
Download
Sample
|