Wednesday, November 23, 2011

SQL SERVER – 2008 – Copy Database With Data – Generate T-SQL For Inserting Data From One Table to Another Table

SQL SERVER – 2008 – Copy Database With Data – Generate T-SQL For Inserting Data From One Table to Another Table


Just about a year ago, I had written on the subject of how to insert data from one table to another table without generating any script or using wizard in my article SQL SERVER – Insert Data From One Table to Another Table – INSERT INTO SELECT – SELECT INTO TABLE. Today, we will go over a similar question regarding how to generate script for data from database as well as table. SQL Server 2008 has simplified everything.

Let us take a look at an example where we will generate script database. In our example, we will just take one table for convenience.

Right Click on Database >> Tasks >> Generate Scripts >>







This will pop up Generate SQL Server Scripts Wizards >> Click on Next >> Select Database >> This will bring up a screen that will suggest to Choose Script Option.




On Choose Script Option Screen of Script Wizard under section Table/View Options Look at Script Data row and Turn the Option to True.




The Next Screen will ask about object types. Select all the objects that are required in the generated script. Depending on the previous screen it will show few more screen requesting details about the objects required in script generation.







On the very last screen it will request output options. Select the desired output options of Script to file, Script to Clipboard or Script New Query Window.3




Clicking on Finish button will generate a review screen containing the required objects along with script generating data.





Clicking on Finish button one more time will generate the requested output.





Similarly, if you want to generate data for only one table, you can right click on the table and follow almost a similar wizard. I am sure this neat feature will help everybody who has been requesting for it for a long time.

Monday, November 21, 2011

ASP.NET: How to open confirm box from codebehind or server side

I see many times people asking this question "How to open confirm box from codebehind or server side". Basically this situation comes when after performing some server side operation you need to show "Confirm" box to the client and if the user say OK then we need to fire the server side code again. In this blog I will show the same, actually in reality there is nothing like calling JS code from server side, a string is written in server side and in the RENDER method that string is thrown to the client so as to be parsed by JS engine at the client side. I have used the following three things to accomplish it:

ClientScript.GetPostBackEventReference
ClientScript.RegisterStartupScript
__doPostBack

ClientScript.GetPostBackEventReference: Returns a string that can be used in a client event to cause postback to the server.

ClientScript.RegisterStartupScript: Registers the startup script with the Page object.

_doPostBack: It is ASP.NET's way of doing javascript postbacks . The first argument is eventTarget, which is the control that is triggering the action. The second argument is event args means any additional information you might want to send with your postback.

Below is the sample code:
<%@ Page Language="C#" %>















Let's start with button's click handler first:
protected void btnFoo_OnClick(object sender, EventArgs e)
{
//Do your stuff here.....


//Below is the code to initiate the modal
var sb = new StringBuilder();
sb.AppendFormat("var foo = window.confirm('Do you want to proceed ?');\n");
sb.Append("if (foo)\n");
sb.Append("__doPostBack('MyConfirmationPostBackEventTarget', foo);\n");
ClientScript.RegisterStartupScript(GetType(), "MyScriptKey", sb.ToString(), true);

}

This is the point where we decide to throw confirm box logic to the client. Here I have made the string to be rendered to the client as JS code. Now when the user presses OK in the confirm box _doPostBack method will called in JavaScript and postback will take place and this is due to ClientScript.GetPostBackEventReference(this, string.Empty) which we wrote in Page Load. Now let's move to the code which will be fired during the next postback (you can say after clicking OK of confirm box)
if (IsPostBack)
{
string eventTarget = Request["__EVENTTARGET"] ?? string.Empty;
string eventArgument = Request["__EVENTARGUMENT"] ?? string.Empty;

switch (eventTarget)
{
case "MyConfirmationPostBackEventTarget":
if (Convert.ToBoolean(eventArgument))
{
AfterUserConfirmationHandler();
}
break;
}
}

Now remember the "__doPostBack('MyConfirmationPostBackEventTarget', foo)" which we called. Here "MyConfirmationPostBackEventTarget" is the event target and "foo" is the event args. So in the server side we checked if it is post back, event target is "MyConfirmationPostBackEventTarget" and eventArgument is true we will fire our server side code. That's it we are done with our task which we need to perform.

Wednesday, November 16, 2011

Enable or disable all controls in the page-C#

Using the code

ChangeControlStatus(false) ;

The Method ChangeControl status accepts a boolean parameter .The parameter value can be set to True/False. When the Parameter value is false all the Controls are disabled and vice versa.
Collapse | Copy Code

private void ChangeControlStatus(bool status)
{

foreach (Control c in Page.Controls)
foreach (Control ctrl in c.Controls)

if (ctrl is TextBox)

((TextBox)ctrl).Enabled = status;

else if (ctrl is Button)

((Button)ctrl).Enabled = status;

else if (ctrl is RadioButton)

((RadioButton)ctrl).Enabled = status;

else if (ctrl is ImageButton)

((ImageButton)ctrl).Enabled = status;

else if (ctrl is CheckBox)

((CheckBox)ctrl).Enabled = status;

else if (ctrl is DropDownList)

((DropDownList)ctrl).Enabled = status;

else if (ctrl is HyperLink)

((HyperLink)ctrl).Enabled = status;

}
private void ClearControls()
{
foreach(Control c in Page.Controls)
{
foreach (Control ctrl in c.Controls)
{
if (ctrl is TextBox)
{
((TextBox)ctrl).Text = string.Empty;
}
}
}
}

Calling the Method

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

ChangeControlStatus(false);
}

ASP.NET authentication and authorization





Before proceeding ahead we need to understand four important vocabularies which you will see in this article again and again: - authentication, authorization, principal and identity. Let’s first start with authentication and authorization. If you search in www.google.com for the dictionary meaning of authentication and authorization, you will land up with something below:-

Authentication: - prove genuineness

Authorization: - process of granting approval or permission on resources.

The same dictionary meaning applies to ASP.NET as well. In ASP.NET authentication means to identify the user or in other words its nothing but to validate that he exists in your database and he is the proper user.
Authorization means does he have access to a particular resource on the IIS website. A resource can be an ASP.NET web page, media files (MP4, GIF, JPEG etc), compressed file (ZIP, RAR) etc.
So the first process which happens is authentication and then authorization. Below is a simple graphical representation of authentication and authorization. So when the user enters ‘userid’ and ‘password’ he is first authenticated and identified by the user name.
Now when the user starts accessing resources like pages, ASPDOTNETauthentication, videos etc, he is checked whether he has the necessary access for the resources. The process of identifying the rights for resources is termed as ‘Authorization’.
 
http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/1.jpg
To put it in simple words to identify “he is shiv” is authentication and to identify that “Shiv is admin” is authorization.
 
At any moment of time if you want to know who the user is and what kind of authentication type he using you can use the identity object. If you want to know what kind of roles it’s associated with then we need to use the principal object. In other words to get authentication details we need to the identity object and to know about authorization details of that identity we need the principal object.
 
http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/2.jpg

For instance below is a simple sample code which shows how to use identity and principal object to display name and check roles.
 
http://www.codeproject.com/images/minus.gifCollapse | Copy Code
Response.Write(User.Identity.Name +"<br>");
Response.Write(User.Identity.AuthenticationType + "<br>");
Response.Write(User.Identity.IsAuthenticated + "<br>");
Response.Write(User.IsInRole("Administrators") + "<br>");

Now if you run this code in IIS under anonymous mode it will display no details as shown below.
 
http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/3.jpg
If you run the above code in IIS using some authentication mode like one shown below “Basic authentication” it will show all the details as shown below.
http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/4.jpg
There are three ways of doing authentication and authorization in ASP.NET:-
Windows authentication: - In this methodology ASP.NET web pages will use local windows users and groups to authenticate and authorize resources.

Forms Authentication: - This is a cookie based authentication where username and password are stored on client machines as cookie files or they are sent through URL for every request. Form-based authentication presents the user with an HTML-based Web page that prompts the user for credentials.

• Passport authentication :- Passport authentication is based on the passport website provided
by the Microsoft .So when user logins with credentials it will be reached to the passport website ( i.e. hotmail,devhood,windows live etc) where authentication will happen. If Authentication is successful it will return a token to your website.

Anonymous access: - If you do not want any kind of authentication then you will go for Anonymous access.

GenericPrincipal and GenericIdentity objects represent users who have been authenticated using Forms authentication or other custom authentication mechanisms. With these objects, the role list is obtained in a custom manner, typically from a database.
FormsIdentity and PassportIdentity objects represent users who have been authenticated with Forms and Passport authentication respectively.
 
When you configure your ASP.NET application as windows authentication it will use local windows user and groups to do authentication and authorization for your ASP.NET pages. Below is a simple snap shot which shows my windows users and roles on my computer.
 
http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/5.jpg
We will do a small sample to get a grasp of how authentication and authorization works with windows. We will create 2 users one ‘Administrator’ and other a simple user with name ‘Shiv’. We will create two simple ASPX pages ‘User.aspx’ page and ‘Admin.aspx’ page. ‘Administrator’ user will have access to both ‘Admin.aspx’ and ‘User.aspx’ page , while user ‘Shiv’ will only have access to ‘User.aspx’ page.
http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/6.jpg
Step 1:- Creation of web site.

The next step is to create a simple web site with 3 pages (User.aspx, Admin.aspx and Home.aspx) as shown below.
 
http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/7.jpg
Step 2:- Create user in the windows directory
 
The next step is we go to the windows directory and create two users. You can see in my computer we have ‘Administrator’ and ‘Shiv’.
 
http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/8.jpg
Step 3:- Setup the ‘web.config’ file
 
In ‘web.config’ file set the authentication mode to ‘Windows’ as shown in the below code snippets.
 
http://www.codeproject.com/images/minus.gifCollapse | Copy Code
<authentication mode="Windows"/>

We also need to ensure that all users are denied except authorized users. The below code snippet inside the authorization tag that all users are denied. ‘?’ indicates any
http://www.codeproject.com/images/minus.gifCollapse | Copy Code
unknown user.
<authorization>
<deny users="?"/>
</authorization>

Step 4:- Setup authorization
We also need to specify the authorization part. We need to insert the below snippet in the ‘web.config’ file stating that only ‘Administrator’ users will have access to
http://www.codeproject.com/images/minus.gifCollapse | Copy Code
‘Admin.aspx’ pages.
<location path="Admin.aspx">
<system.web>
<authorization>
<allow roles="questpon-srize2\Administrator"/>
<deny users="*"/>
</authorization>
</system.web>
</location>

Step 5:-Configure IIS settings
The next step is to compile the project and upload the same on an IIS virtual directory. On the IIS virtual directory we need to ensure to remove anonymous access and check the integrated windows authentication as shown in the below figure.
 
http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/9.jpg
 
Now if you run the web application you will be popped with a userid and password box as shown below.
http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/10.jpg
Once you enter credentials you should be able to see home.aspx as shown below.
http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/11.jpg
In case you are not an administrator (i.e in this case its ‘shiv’) and you navigate to ‘Admin.aspx’ it will throw an error as shown in the below figure.
http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/12.jpg
In case you want to read who the user is and with what authorization rights has he logged in you can use ‘WindowsPrincipal’ and ‘WindowsIdentity’. These two objects represent users who have been authenticated with Windows authentication. You can also get the roles these users have.
 
In the above step by step article you must have noticed the below options on IIS (Integrated, digest and basic). These three checkboxes decide how the windows username and password credentials are passed from the client desktop to the IIS.
There are three different way of passing the windows username and password to IIS:-
• Basic
• Digest
• Windows
In the coming session we will understand in depth what these 3 options are.
 
http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/13.jpg
When basic authentication is selected the ‘userid’ and ‘password’ are passed by using Base64 encoded format . i.e. why the name is basic authentication. ‘Base64’ is a encoding and not encryption. So it’s very easy to crack. You can read more about ‘Base64’ encoding at http://en.wikipedia.org/wiki/Base64 . Its a very weak form of protection.
 
http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/14.jpg

http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/15.jpg
Below is a small demonstration how easy it is to crack a basic authentication. You can see in the below figure we have checked ‘Basicauthentication’ check and we ran the fiddler tool to see the data.
http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/16.jpg
We then copied the ‘Authorization:Basic’ data and ran the below program. LOL, we can see our windows userid and password.
http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/17.jpg
Below is the code snippet of how to decode ‘Base64’ encoding.
 
http://www.codeproject.com/images/minus.gifCollapse | Copy Code
public static string DecodeFrom64(string encodedData)
{

byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);

string returnValue = System.Text.Encoding.ASCII.GetString(encodedDataAsBytes);

return returnValue;}

Basic authentication in other words ‘Base64’ encoding is used to transmit binary data and convert them to text so that they can run over the network. Some protocols may interpret your binary data as control characters. For instance the FTP protocol for certain combination of binary characters can interpret the same as FTP line endings.

At the end of the days it’s not an encryption algorithm it’s an encoding mechanism. That’s why in our previous section we demonstrated how easy it was to decode basic authentication.
 
The problem associated with basic authentication is solved by using digest authentication. We saw in our previous section how easy it was to crack basic authentication. Digest authentication transfers data over wire as MD5 hash or message digest. This hash or digest is difficult to dechiper.
In other words digest authentication replaces the lame basic authentication.
 
http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/18.jpg
Said and done there one of the big problems of digest authentication is it’s not supported on some browsers.
 
Integrated Windows authentication (formerly called NTLM, and also known as Windows NT Challenge/Response authentication) uses either Kerberos v5 authentication or NTLM authentication, depending upon the client and server configuration.
(The above paragraph is ripped from http://msdn.microsoft.com/en-us/library/ff647076.aspx  ).
Let’s try to understand what NTLM and Kerberos authentication is all about and then we will try to understand other aspects of integrated authentication.
NTLM is a challenge response authentication protocol. Below is how the sequence of events happens:-
• Client sends the username and password to the server.
• Server sends a challenge.
• Client responds to the challenge with 24 byte result.
• Servers checks if the response is properly computed by contacting the domain controller.
• If everything is proper it grants the request.
 
http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/19.jpg
Kerberos is a multi-hounded (3 heads) who guards the gates of hades. In the same way Kerberos security has 3 participants authenticating service, service server and ticket granting server. Let’s try to understand step by step how these 3 entities participate to ensure security.
http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/20.jpg
Courtesy: - http://24-timepass.com/postimg/three-headed-dog.jpg
Kerberos uses symmetric key for authentication and authorization. Below is how the things work for Kerberos:-

• In step 1 client sends the username and password to AS (Authenticating service).
• AS authenticates the user and ensures that he is an authenticated user.
• AS then asks the TGT (Ticket granting service) to create a ticket for the user.
• This ticket will be used to verify if the user is authenticated or not. In other words in further client interaction no password will be sent during interaction.
 
http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/21.jpg
One of the things which you must have noticed is that integrated, digest and basic authentication are check boxes. In other words we can check all the three at one moment of time. If you check all the 3 options at one moment of time depending on browser security support one of the above methods will take precedence.
 
http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/222.jpg
Let’s understand how the security precedence works as per browser security.
• Browser makes a request; it sends the first request as Anonymous. In other words it does not send any credentials.

• If the server does not accept Anonymous IIS responds with an "Access Denied" error message and sends a list of the authentication types that are supported by the browser.

• If Windows NT Challenge/Response is the only one supported method then the browser must support this method to communicate with the server. Otherwise, it cannot negotiate with the server and the user receives an "Access Denied" error message.

• If Basic is the only supported method, then a dialog box appears in the browser to get the credentials, and then passes these credentials to the server. It attempts to send these credentials up to three times. If these all fail, the browser is not connected to the server.

• If both Basic and Windows NT Challenge/Response are supported, the browser determines which method is used. If the browser supports Windows NT Challenge/Response, it uses this method and does not fall back to Basic. If Windows NT Challenge/Response is not supported, the browser uses Basic.
You can read more about precedence from http://support.microsoft.com/kb/264921.

In order words the precedence is:-

1. Windows NT challenge ( Integrated security)
2. Digest
3. Basic
 


Browse support
Authentication mechanism
Basic
Almost all browsers
Weak uses Base64.
Digest
 IE 5 and later version
Strong MD5
Integrated windows

• Kerberos
 IE5 and above
 Ticket encryption using AD , TGT and KDC
• Challenge / response
IE5 and above
Send a challenge

Forms authentication is a cookie/URL based authentication where username and password are stored on client machines as cookie files or they are sent encrypted on the URL for every request if cookies are not supported.
Below are the various steps which happen in forms authentication:-
• Step 1:- User enters “userid” and “password” through a custom login screen developed for authentication and authorization.
• Step 2:- A check is made to ensure that the user is valid. The user can be validated from ‘web.config’ files, SQL Server, customer database, windows active directory and various other kinds of data sources.

• Step 3:- If the user is valid then a cookie text file is generated on the client end. This cookie test file signifies that the user has been authenticated. Hence forth when the client computer browses other resources of your ASP.NET site the validation is not conducted again. The cookie file indicates that the user has logged in.
 
http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/23.jpg
So let’s understand step by step how to configure forms authentication. As said in the previous sections you can store user in ‘web.config’ files. Definitely it’s not the best way to store user in “web.config” files but it will really help us to understand forms authentication. Once we understand the same we can then move ahead to better improvised versions of forms authentication.

Step 1:- The first thing we need to do is make an entry in to the web.config file with authentication mode as forms as shown below. We need to also provide the following things :-

• LoginUrl :- This property helps us to provide the start page of authentication and authorization.

• defaultUrl :- Once the user is validated he will be redirected to this value , currently its “Home.aspx”.

• Cookieless :- As said previously forms authentication uses cookies. There are four ways by which you can change this behavior :-

oAutoDetect: - Depending on your browser configuration it can either use cookies or pass the authentication information encrypted via browser URL.

o UseCookies: - You would like the forms authentication mechanism to create cookie when the authentication is successful.

o UseURI :- You would like to pass data encrypted via the browser URL query string.

o UseDeviceProfile :- This is the default value. When you set this value the forms authentication mechanism will do look up at
 “C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG\Browsers” to see if the browser support cookies and then decides whether it should use cookies or should not. In other words it does not check on actual runtime if the browser has cookies enabled.

• Credentials: - In the credentials tag we have also some users with name and password. As said previously we will first use forms authentication with username’s stored in web.config files.
 
http://www.codeproject.com/images/minus.gifCollapse | Copy Code
<authentication mode="Forms">
<forms loginUrl="Login.aspx" timeout="30" defaultUrl="Home.aspx" cookieless="AutoDetect">
<credentials passwordFormat="Clear">
<user name="Shiv" password="pass@123"/>
<user name="Raju" password="pass@123"/>
</credentials>
</forms>
</authentication>

Different customization values for ‘cookieless’ property.
 
http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/24.jpg

If you set the cookieless as ‘UseDeviceProfile” it will use the browser data from the below file. You can see how Ericsson browser does not support cookies. So if any one connects with ericsson browser and the value is ‘UseDeviceProfile” , forms authentication will pass data through query strings.

http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/25.jpg
Step 2:- Once you have set the “forms” tag values , it’s time to ensure that anonymous users are not able to browse your site. You can set the same by using the authorization tag as shown in the below code snippet.
 
http://www.codeproject.com/images/minus.gifCollapse | Copy Code
<authorization>
<deny users="?"/>
</authorization>

Step 3:- We also need to define which user have access to which page. In this project we have created two pages “Admin.aspx” and “User.aspx”. “Admin.aspx” is accessible to only user “Shiv” while “Admin.aspx” and “User.aspx” is accessible to both the users.

Below web.config settings show how we can set the user to pages.
 
http://www.codeproject.com/images/minus.gifCollapse | Copy Code
<location path="Admin.aspx">
<system.web>
<authorization>
<allow users="Shiv"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
<location path="User.aspx">
<system.web>
<authorization>
<allow users="Shiv"/>
<allow users="Raju"/>
<deny users="*"/>
</authorization>
</system.web>
</location>

Step 4 :- We now create our custom page which will accept userid and password.
 
http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/26.jpg
In the button click we provide the below code. The “FormsAuthentication.Authenticate” looks in the web.config the username and passwords. The “FormsAuthentication.RedirectFromLoginPage” creates cookies at the browser end.
http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/27.jpg
If you run your application , enter proper credentials , you should be able to see a cookie txt file created as shown in the below figure.
http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/28.jpg
If you disable cookies using the browser settings, credentials will be passed via query string as shown in the below figure.
http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/29.jpg

http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/30.jpg
In order to do custom authentication you need to need to just replace “FormsAuthentication.Authenticate” statement with your validation. For instance in the below code we have used ‘clsUser’ class to do authentication but we have yet used the cookie creation mechanism provided by ‘FormAuthentication’ system.
http://www.codeproject.com/images/minus.gifCollapse | Copy Code
clsUser objUser = new clsUser();
if (objUser.IsValid(txtUser.Text,txtPass.Text))
{
FormsAuthentication.RedirectFromLoginPage(txtUser.Text, true);
}

We have used forms authentication mechanism to generate cookie which has minimized lot of our development effort. Many other tasks we are still performing like:-
• Creation of user and roles tables.
• Code level implementation for maintaining those tables.
• User interface for userid and password.

We are sure you must have done the above task for every project again and again. Good news!!! All the above things are now made simple with introduction of membership and roles. To implement ASP.NET membership and roles we need to do the following steps :-

• Run aspnet_regsql.exe from ‘C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727’ folder. Enter SQL Server credentials and run the exe. This will install all the necessary stored procedures and tables as shown in figure ‘Object created by aspnet_regsql.exe’
 
http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/31.jpg

• Specify the connection string in the ‘web.config’ file where your ASP.NET roles tables and stored procedures are created.
http://www.codeproject.com/images/minus.gifCollapse | Copy Code
<connectionStrings>
<remove name="LocalSqlServer1"/>
<add name="LocalSqlServer1" connectionString="Data Source=localhost;Initial
Catalog=test;Integrated Security=True"/>
</connectionStrings>


• Specify the ASP.NET membership provider and connect the same with the connection string provided in the previous step.
http://www.codeproject.com/images/minus.gifCollapse | Copy Code
<membership>
<providers>
<remove name="AspNetSqlMembershipProvider"/>
<add name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider, System.Web,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="LocalSqlServer1" enablePasswordRetrieval="false"
enablePasswordReset="true" applicationName="/" minRequiredPasswordLength="7"/>

</providers>
</membership>

• We also need to specify the role provider and connect the same with the connection string provided in the previous session.
 
http://www.codeproject.com/images/minus.gifCollapse | Copy Code
<roleManager enabled="true">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" connectionStringName="LocalSqlServer1"
applicationName="/" type="System.Web.Security.SqlRoleProvider, System.Web,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</providers>
</roleManager>

Now you can use the “Membership” class to create users and roles as shown in the below 2 figures.
 
http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/32.jpg

http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/33.jpg

You can get a feel how easy it is to use develop authentication and authorization by using forms authentication
 and ASP.NET membership and roles.
 
Authentication and authorization in any application needs 2 things:-
• Mechanism by which you can generate a cookie: - Provided by Forms authentication.

• Custom tables in SQL Server to store user and roles: - Provided by ASP.NET provider and roles.

In other words by using the combination of ticket generation via forms authentication and ASP.NET provider and roles we can come up with a neat and quick solution to implement authentication and authorization in ASP.NET applications.
 
Many time we would like to implement single sign on across multiple sites. This can be done using forms authentication. You can implement forms authentication in both the websites with same machine key. Once the validation is done in one website a cookie text file will be created. When that user goes to the other website the same cookie file will used to ensure that the user is proper or not.
Please note you need to have same machine key in both the web.config files of your web application.
 
http://www.codeproject.com/images/minus.gifCollapse | Copy Code
<machineKey
validationKey="C50B3C89CB21F4F1422FF158A5B42D0E8DB8CB5CDA1742572A487D9401E340
0267682B202B746511891C1BAF47F8D25C07F6C39A104696DB51F17C529AD3CABE"
decryptionKey="8A9BE8FD67AF6979E7D20198CFEA50DD3D3799C77AF2B72F"
validation="SHA1" />

You can see a very detail article on Single sign at http://msdn.microsoft.com/en-us/library/ms972971.aspx . You can also download the code from http://download.microsoft.com/download/B/7/8/B78D1CED-2275-4AEE-B0BE-0DEA1A2A9581/MSDNEnterpriseSecurity.msi 
The above discusses how a internal intranet and internet application login through one single sign-on facility.
 
http://www.codeproject.com/KB/aspnet/ASPDOTNETauthentication/34.jpg

Passport authentication is based on the passport website provided by the Microsoft .So when user logins with credentials it will be reached to the passport website ( i.e. hotmail,devhood,windows live etc) where authentication will happen. If Authentication is successful it will return a token to your website.
I am leaving this section for now, will update in more details soon