Tuesday 31 January 2012

Forms Authentication in ASP.NET with C#: Basic


This article describe how to use Forms Authentication in ASP.NET with C#. After reading this article you will be able to create a web application with Forms Authentication. This article also includes downloadable sample project with source code.

Download


 Download source code for Forms Authentication in ASP.NET with C#: Basic

Introduction
Forms Authentication is a mechanism to allow only authenticated user with valid credential to view a particular page or group of pages/folders and stop unauthenticated or anonymus use outside the secure boundry. Forms authentication uses an authentication ticket that is created when a user logs on to a site, and then it tracks the user throughout the site. The forms authentication ticket is usually contained inside a cookie. However, cookieless forms authentication is also possible that works by passing user ticket in query strings.
This article describe how to create a simple Forms Authentication website with Default, Secure and Login page. I am going to explain in easy to follow steps.
Step - 1 - Create Login page
Create a new website in Visual Studio or Visual Web Developer by going through File > New Web Site ... Right click Solution Explorer and add a new page called Default.aspx and change its title to Home Page. Now again add one more page called Login.aspx and drag Login control from the toolbar (under Login section). Your page should look like below (Picture - 1)
Picture - 1

Don't worry about Home Page | Secure Page link and other text now (I have created a user control and used that user control into my master page so that it displays in all pages that will use my master page). Also ignores the formatting as it is appearing in the picture, however you can select any formatting using Smart tag of the Login control. As long as User Name, Password, CheckBox and Login button is displaying for you that is fine.
For the exact look and feel of your Login control you can copy-paste following code.

<asp:Login ID="Login1" runat="server" BackColor="#F7F6F3" BorderColor="#E6E2D8" 
BorderPadding="4" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana"
Font-Size="0.8em" ForeColor="#333333" onauthenticate="Login1_Authenticate">
<TextBoxStyle Font-Size="0.8em" />
<LoginButtonStyle BackColor="#FFFBFF" BorderColor="#CCCCCC" BorderStyle="Solid"
BorderWidth="1px" Font-Names="Verdana" Font-Size="0.8em" ForeColor="#284775" />
<InstructionTextStyle Font-Italic="True" ForeColor="Black" />
<TitleTextStyle BackColor="#5D7B9D" Font-Bold="True" Font-Size="0.9em"
ForeColor="White" />
</asp:Login>
Double click Login control and you should see the code behind file of the Login.aspx page. Notice that Login1_Authenticate event will be automatically created (If it has not been created for any reason just copy-paste following code and go to the Source view of the Login.aspx and add onauthenticate="Login1_Authenticate" attribute in the Login control .
Namespace to use
FormsAuthentication object exists in following namespace.

System.Web.Security;

/// <summary>
/// Fires when Login button will be clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
bool authenticated = AuthenticateMe(Login1.UserName, Login1.Password, Login1.RememberMeSet)
if (authenticated)
{
FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet)
}
}
/// <summary>
/// Authenticate user
/// </summary>
/// <param name="userName"></param>
/// <param name="password"></param>
/// <param name="rememberUserName"></param>
/// <returns></returns>
private bool AuthenticateMe(string userName, string password, bool rememberUserName)
{
// just hard code the username for this demo 
// in real scenario you should call your object and validate username and password againt th database or whichever data source you are using
string localUserName = "user";
string localPassword = "password";
if (userName.Equals(localUserName) && password.Equals(localPassword))
{
return true;
}
else
{
return false;
}
}

In the Login1_Authenticate event I am calling AuthenticateMe function that is validating the user for their username and password and returning true or false. For simplicity I have just hard coded username and password, in real scenario you should validate them using your datasource (database or active directory or whatever). If AuthenticateMe function returns true I am using FormsAuthentication.RedirectFromLoginPage method of FormsAuthentication object and passing username and Remember Me checkbox status (Don't get involved into it, Its simple. If checkbox will be checked user will be able to continue their session after closing and reopening their browser else not).


Step - 2 - Create Web.Config file setting
Now modify your web.config file. Just add Authentication and Authorization tag inside <system.web> like following.
<authentication mode="Forms">
<forms defaultUrl="default.aspx" loginUrl="~/login.aspx" slidingExpiration="true" timeout="20"></forms>
</authentication>
<authorization>

</authorization>

Let me explain in brief what are different attributes of <forms> tag are.
defaultUrl is the name of the page where user will be redirected by default after they are logging in from home page or not secured page.
loginUrl is is the name of the page where user will be redirected when they will try to enter into secure page/folders of the website.
slidingExpiration is the attribute that defines whether you want users session to slide if they are continuing their work on secure page.
timeout value defines duration (in minutes) of the user session after that user session will expire (If slidingExpiration is false otherwise timeout is count after last hit of user to the website).
Step - 3 - Create a Secure folder
Right click your website in Solution explorer and add a folder named Secure. Add a .aspx page and name it like SecurePage.aspx. Again Add a web.config file inside it and write following code into it inside <system.web> tag.
<authorization>
<deny users="?"/>
</authorization>
The deny tag inside authorizaton tag is specifying that this (Secure) folder is denied for all anonymus user and only validated user should be able to access any content of this folder.
Step - 4 - Run your application
Right click your SecurePage.aspx under Secure folder and select Set As Start Page. Run your application and you should see your browser something like above picture (Picture - 1). You can notice that instead of directly going to SecurePage.aspx, you have been redirected to Login.aspx. This is because you are not authenticated yet and you have specified Secure folder as the folder where anonymus users are not allowed.  Enter username and password (in my case it is "user" and "password"), click Login button and you will be redirected to SecurePage.aspx. Try entering wrong username and password and you will see a message something like "Your login attempt ...".
So you are secure now :). Download the attachment of this article and you can see full implementation of Forms Authentication described in this article along with usage of LoginView, LoginStatus and LoginName controls.
Enjoy !!!
To implement Role Based Forms Authentication See http://www.dotnetfunda.com/articles/article141.aspx

Sunday 29 January 2012

Javascript Modal Popups

http://www.modalpopups.com/download.ashx?file=ModalPopups_0_2.zip


Javascript Modal Popups offers you a free javascript with commonly used modal popups. No CSS. No images. Auto size body. Very easy to use.
This page show demo javascript code for functions: Alert, Confirm, YesNoCancel, Prompt, Indicator and Custom.
It shows you the options to customize the look.
In order for all your modals to have the same behaviour you can set defaults with the ModalPopups.SetDefaultsfunction.
Defaults:
shadow: true, shadowSize: 5, shadowColor: "#333333", backgroundColor: "#CCCCCC", borderColor: "#999999", titleBackColor: "#C1D2E7", titleFontColor: "#15428B", popupBackColor: "#C7D6E9", popupFontColor: "black", footerBackColor: "#C1D2E7", footerFontColor: "#15428B", okButtonText: "OK", yesButtonText: "Yes", noButtonText: "No", cancelButtonText: "Cancel", fontFamily: "Verdana,Arial", fontSize: "9pt"
To set Dutch Language buttons throughout your application, just create a .js and include it in your page (below the include of ModalPopups.js)
ModalPopups.SetDefaults( { yesButtonText: "Ja", noButtonText: "Nee", okButtonText: "OK", cancelButtonText: "Annuleren" } );
This page uses syntax highlighter.

Alert, example 1
  1. function ModalPopupsAlert1() {  
  2.     ModalPopups.Alert("jsAlert1",  
  3.         "Save address information",  
  4.         "<div style='padding:25px;'>The address information has been saved succesfully<br/>" +  
  5.         "to the customer database...<br/></div>",   
  6.         {  
  7.             okButtonText: "Close"  
  8.         }  
  9.     );  
  10. }  

Alert, example 2
  1. function ModalPopupsAlert2() {  
  2.     ModalPopups.Alert("jsAlert2",  
  3.         "Save address information",  
  4.         "<div style='padding:25px;'>The address information has been saved succesfully<br/>" +  
  5.         "to the customer database...<br/></div>",  
  6.         {  
  7.             okButtonText: "Close",  
  8.             backgroundColor: "Yellow",  
  9.             shadowSize: 15,  
  10.             fontFamily: "Courier New",  
  11.             fontSize: "9pt"  
  12.         }  
  13.     );  
  14. }  

Alert, example 3
  1. function ModalPopupsAlert3() {  
  2.     ModalPopups.Alert("jsAlert3",  
  3.         "Save address information",  
  4.         "<div style='padding:25px;'>The address information has been saved succesfully<br/>" +  
  5.         "to the customer database...<br/></div>",  
  6.         {  
  7.             titleBackColor: "#A1B376",  
  8.             titleFontColor: "white",  
  9.             popupBackColor: "#E9E8CF",  
  10.             popupFontColor: "black",  
  11.             footerBackColor: "#A1B376",  
  12.             footerFontColor: "white"  
  13.         }  
  14.     );  
  15. }  

Confirm
  1. function ModalPopupsConfirm() {  
  2.     ModalPopups.Confirm("idConfirm1",  
  3.         "Confirm delete address information",  
  4.         "<div style='padding: 25px;'>You are about to delete this address information.<br/><br/><b>Are you sure?</b></div>",   
  5.         {  
  6.             yesButtonText: "Yes",  
  7.             noButtonText: "No",  
  8.             onYes: "ModalPopupsConfirmYes()",  
  9.             onNo: "ModalPopupsConfirmNo()"  
  10.         }  
  11.     );  
  12. }  
  13. function ModalPopupsConfirmYes() {  
  14.     alert('You pressed Yes');  
  15.     ModalPopups.Close("idConfirm1");  
  16. }  
  17. function ModalPopupsConfirmNo() {  
  18.     alert('You pressed No');  
  19.     ModalPopups.Cancel("idConfirm1");  
  20. }  

YesNoCancel
  1. function ModalPopupsYesNoCancel() {  
  2.     ModalPopups.YesNoCancel("idYesNoCancel1",  
  3.         "Confirm close of document",  
  4.         "<div style='padding: 25px;'><p>You are about to close this document.<br/>" +   
  5.         "If you don't save this document, all information will be lost.</p>" +   
  6.         "<p><b>Close document?</b></p></div>",   
  7.         {  
  8.             onYes: "ModalPopupsYesNoCancelYes()",  
  9.             onNo: "ModalPopupsYesNoCancelNo()",  
  10.             onCancel: "ModalPopupsYesNoCancelCancel()"  
  11.         }  
  12.     );  
  13. }  
  14. function ModalPopupsYesNoCancelYes() {  
  15.     alert('You pressed Yes');  
  16.     ModalPopups.Close("idYesNoCancel1");  
  17. }  
  18. function ModalPopupsYesNoCancelNo() {  
  19.     alert('You pressed No');  
  20.     ModalPopups.Cancel("idYesNoCancel1");  
  21. }  
  22. function ModalPopupsYesNoCancelCancel() {  
  23.     alert('You pressed Cancel');  
  24.     ModalPopups.Cancel("idYesNoCancel1");  
  25. }  

Prompt
  1. function ModalPopupsPrompt() {  
  2.     ModalPopups.Prompt("idPrompt1",  
  3.         "Prompt",  
  4.         "Please enter your ID number",    
  5.         {  
  6.             width: 300,  
  7.             height: 100,  
  8.             onOk: "ModalPopupsPromptOk()",  
  9.             onCancel: "ModalPopupsPromptCancel()"  
  10.         }  
  11.     );  
  12. }  
  13. function ModalPopupsPromptOk()  
  14. {  
  15.     if(ModalPopups.GetPromptInput("idPrompt1").value == "") {  
  16.         ModalPopups.GetPromptInput("idPrompt1").focus();  
  17.         return;  
  18.     }  
  19.     alert("You pressed OK\nValue: " + ModalPopups.GetPromptInput("idPrompt1").value);  
  20.     ModalPopups.Close("idPrompt1");  
  21. }  
  22. function ModalPopupsPromptCancel() {  
  23.     alert("You pressed Cancel");  
  24.     ModalPopups.Cancel("idPrompt1");  
  25. }  

Indicator, default
  1. function ModalPopupsIndicator() {  
  2.     ModalPopups.Indicator("idIndicator1",  
  3.         "Please wait",  
  4.         "Saving address information... <br>" +   
  5.         "This may take 3 seconds.",   
  6.         {  
  7.             width: 300,  
  8.             height: 100  
  9.         }  
  10.     );  
  11.               
  12.     setTimeout('ModalPopups.Close(\"idIndicator1\");', 3000);  
  13. }  

Indicator, with custom indicator image
  1. function ModalPopupsIndicator2() {  
  2.     ModalPopups.Indicator("idIndicator2",  
  3.         "Please wait",  
  4.         "<div style=''>" +   
  5.         "<div style='float:left;'><img src='spinner.gif'></div>" +   
  6.         "<div style='float:left; padding-left:10px;'>" +   
  7.         "Saving address information... <br/>" +   
  8.         "This may take 3 seconds." +   
  9.         "</div>",   
  10.         {  
  11.             width: 300,  
  12.             height: 100  
  13.         }  
  14.     );  
  15.               
  16.     setTimeout('ModalPopups.Close(\"idIndicator2\");', 3000);  
  17. }  

Custom (Customized)
  1. function ModalPopupsCustom1() {  
  2.     ModalPopups.Custom("idCustom1",  
  3.         "Enter address information",  
  4.         "<div style='padding: 25px;'>" +   
  5.         "<table>" +   
  6.         "<tr><td>Name</td><td><input type=text id='inputCustom1Name' style='width:250px;'></td></tr>" +   
  7.         "<tr><td>Address</td><td><input type=text id='inputCustom1Address' style='width:250px;'></td></tr>" +   
  8.         "<tr><td>ZipCode</td><td><input type=text id='inputCustom1ZipCode' style='width:100px;'></td></tr>" +   
  9.         "<tr><td>City</td><td><input type=text id='inputCustom1City' style='width:250px;'></td></tr>" +   
  10.         "<tr><td>Phone</td><td><input type=text id='inputCustom1Phone' style='width:250px;'></td></tr>" +   
  11.         "<tr><td>E-Mail</td><td><input type=text id='inputCustom1EMail' style='width:250px;'></td></tr>" +   
  12.         "</table>" +   
  13.         "</div>",   
  14.         {  
  15.             width: 500,  
  16.             buttons: "ok,cancel",  
  17.             okButtonText: "Save",  
  18.             cancelButtonText: "Cancel",  
  19.             onOk: "ModalPopupsCustom1Save()",  
  20.             onCancel: "ModalPopupsCustom1Cancel()"  
  21.         }  
  22.     );  
  23.               
  24.     ModalPopups.GetCustomControl("inputCustom1Name").focus();   
  25. }  
  26. function ModalPopupsCustom1Save() {  
  27.     var custom1Name = ModalPopups.GetCustomControl("inputCustom1Name");   
  28.     if(custom1Name.value == "") {  
  29.         alert("Please submit a name to this form");  
  30.         custom1Name.focus();  
  31.     }  
  32.     else {  
  33.         alert("Your name is: " + custom1Name.value);  
  34.         ModalPopups.Close("idCustom1");  
  35.     }  
  36. }  
  37.   
  38. function ModalPopupsCustom1Cancel() {  
  39.     alert('You pressed Cancel');  
  40.     ModalPopups.Cancel("idCustom1");  
  41. }  

Alert (loadFile: "TextFile.txt")
  1. function ModalPopupsAlert99() {  
  2.     ModalPopups.Alert("jsAlert99",  
  3.         "Save address information",  
  4.         "", {  
  5.             okButtonText: "Close",  
  6.             loadTextFile: "TextFile.txt",  
  7.             width: 500,  
  8.             height: 300});  
  9. }