Most sample codes of Forms Authentication on the web is either hard to
customise or tighten to some built-in stuff, such as some built-in membership
providers. I was doing a WCF projects and found there were no good examples for
me to overcome some difficulties. Finally I work out the following helper class,
public static
class
FormsAuthenticationHelper
{
public static
bool LogUserIn(IEnumerable<string>
roles, string username,
string password)
{
StringBuilder rolesString =
new StringBuilder();
foreach (string
role in roles)
{
rolesString.Append(role.ToString() + ",");
}
// converts all the roles to which the member
belong into a string with role names separated by comma
FormsAuthenticationTicket authTicket =
new
FormsAuthenticationTicket(1, username
, DateTime.Now,
DateTime.Now.AddDays(1),
false, rolesString.ToString());
// creates a custom authentication ticket which
stores the role string in its custom data field
string encryptedTicket =
FormsAuthentication.Encrypt(authTicket);
// encrypts the ticket
HttpCookie authCookie =
new HttpCookie(FormsAuthentication.FormsCookieName,
encryptedTicket);
// creates the custom authentication cookie
HttpContext.Current.Response.Cookies.Add(authCookie);
// adds that cookie into current http response
return true;
}
public static
void Logout()
{
FormsAuthentication.SignOut();
}
///
<summary>
///
/// usuage in
Global.asax:
///
/// void
Application_PostAuthenticateRequest(object sender, EventArgs e)
/// {
///
WebAuthentication.SetCurrentPrincipal();
/// }
///
///
</summary>
public static
void SetCurrentPrincipal()
{
FormsAuthenticationTicket ticket =
GetFormsAuthenticationTicket();
if (ticket ==
null) return;
// tries to get the authentication ticket from
the cookie
string[] roles = ticket.UserData.Split(new
char[] { ','
});
// extracts all the roles from the ticket
GenericPrincipal principal =
new GenericPrincipal(HttpContext.Current.User.Identity,
roles);
// creates a new principal
HttpContext.Current.User = principal;
Thread.CurrentPrincipal = principal;
// replaces current principal with the newly
created one
}
public static
FormsAuthenticationTicket
GetFormsAuthenticationTicket()
{
List<string>
matchedKeys = HttpContext.Current.Request.Cookies.AllKeys
.Where(k => k == FormsAuthentication.FormsCookieName)
.ToList();
if (matchedKeys.Count == 0)
return null;
// tries to retrieve cookie which has default
authentication cookie name from http request
FormsAuthenticationTicket ticket =
FormsAuthentication.Decrypt(
HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value);
// if coookie found extracts the authentication
ticket from the cookie
return ticket;
}
}
It is very easy to use this helper class to implement Forms
Authentication in you own code.
1. Login – Server Side
1.1 ASP.NET
Let’s say you have a login button called btnLogin
protected void
btnLogin_Click(object sender,
EventArgs e)
{
string username = txtUsername.Text.Trim();
string password = txtPassword.Text.Trim();
//
validates the username and password
bool isValidUser = doCustomValidation(username,password);
if (!isValidUser)
return;
List<string>
roles = new List<string>();
roles.Add("ValidUserForProdectedResources");
// you may change that to any role you like
FormsAuthenticationHelper.LogUserIn(roles,
pin.ToString(), password);
Response.Redirect("ProdectedPage.aspx");
}
1.2. WCF
[AspNetCompatibilityRequirements(RequirementsMode
= AspNetCompatibilityRequirementsMode.Allowed)]
public
class DkDataService
: IDkDataService
{
public bool
Login(int pin, string
password)
{
bool isValidUser = doCustomValidation(username,password);
if (!isValidUser)
return false;
List<string>
roles = new List<string>();
roles.Add("ValidUserForProdectedResources");
// you may change that to any role you like
FormsAuthenticationHelper.LogUserIn(roles,
pin.ToString(), password);
Return true;
}
}
PS: You can also do exactly the same things on ASMX service.
To be
continued …