Sunday, 9 December 2012

Authentication IN .NET


Authentication
Authentication is the act of validating a client's identity. In a distributed application environment ability to identify someone that is claiming to be is very critical. It is the starting point of giving access to vital resources in site. Generally this is done by user providing some kind of evidence that known as credentials. Typically, credentials includes a username and a password that use for authentication. Both Internet Information Server (IIS) and ASP.NET provides several authentication schemas. ASP.NET supports four kind of authentication.
1. Windows Authentication
2. Passport Authentication
3. Form Authentication
4. None
When implementing a site, we can select from above four authentication mechanisms.
IIS provides the following authentication schemas
1. Anonymous
2. Basic
3. Digest
4. Integrated Windows authentication
5. Client Certificate Mapping
1. Windows Authentication

Every time when creating an ASP.NET Web application or Web services the default authentication model will be Windows Authentication. To make use of the Windows Authentication, the Web.config file needs to be configured as below:





The windows authentication provider relies upon Internet Information Server (IIS) to perform the required authentication for a user. Then after the user gets authenticated, IIS passes a security token to ASP.NET. There are several ways that you can use windows authentication, Basic Authentication, Digest Authentication, Integrated Windows Authentication (NTL/Kerberos) or X.509 Client Certificates. To use these authentication options the user need a valid account in windows domain or within Active Directory.
To use Windows Authentication, you need to configure the IIS to turn off the anonymous access. Allowing anonymous access is the default for authentication. It can be done as shown below.
Click Start > Run > type inetmgr. This will open the Internet Information Services window. Select the Default Web Sites and navigate to the virtual directory of interest. Select all the files by selecting the virtual directory or the particular file (.aspx, .asmx) and right click the directory or file. Select Properties > Directory Security (Figure 1).

Figure 1
Now under the Anonymous access and authentication control, click the Edit button. The Authentication Methods dialog box will display as shown in Figure 2

Figure 2
Using the Authentication Method dialog box configure how a user can access the virtual directory or files. To pass the users credentials via HTTP headers, you can use Basic authentication or Digest authentication.
Anonymous Authentication

Anonymous authentication is perfect for public sites that dose not required identifying the users. The user doesn't need to pass a username and a password to server to access the information. In this scenario all users have access for the site and there won't be any restrictions for the users. When anonymous authentications is used the application thread will run either
1. Anonymous internet account IUSR_MACHINENAME
2. A account configured at IIS for anonymous users
3. or IIS system account
This mechanism wont be suitable if user need to restrict from accessing recourse on base of there credentials.
To implement the Anonymous authentication select the Anonymous access in the Authentication methods window at IIS. (A sample of Authentication methods window is displayed in figure 2) At the same time configure the ASP.NET using Web.config file to use Windows authentication as shown below.





Basic Authentication

Basic authentication is an HTTP standard. The username and password that passes through the channel is clear text. This uses the base64 encoding. This is human readable and there are no secret keys being used for encoding. IIS will check the user name and password to an account on the web server and produce an access token.
This token will be used to do an ACL base security check. When user try to access a file or a directory that allows Basic authentication unauthorized, it will display an error message with 401 status codes indicating that authentication is required. Windows authentication works virtually with all browsers and it works well with firewalls.
The downside is using unencrypted channel for gain access for the server there is noting to prevent request from being intercepted. Because of this the credentials should be passes in a secure channel using SSL to make it less venerable for interception.
To implement the Basic authentication select the Basic Authentication in the Authentication methods window at IIS. At the same time users should have "log on locally" privilege on the web server. (A sample of Authentication methods window is displayed in figure 2). Configure the ASP.NET using Web.config file to use Windows authentication as shown below.





A Dialog box will display to enter credentials when user tries to access the protected site.

Figure 3
User will get access for the resources if he/she authenticated. Otherwise the following error message will be displayed.

Figure 4
Digest Authentication

This is bit similar to the Basic authentication. When user tries to access a file or a directory protected by Digest authentication a pop up dialog box will be displays asking for the user name and the password. Then the credentials that user enter will assign an identity to the request. The biggest different with Basic and Digest is the Digest doesn't transmit information in clear text. It transmits information in a cryptographically secure way. The advantage is you can use it over unencrypted channel.
When user enters the user name and password in the dialog box the user name will be transmit to the server with a hash or "digest" computed from the combined user name, password and nonce. Then the server will create its own hash on the user name, password and nonce and authenticate against each. The password that server use dose not coming from the user, it is what stored in the server side for that particular user name. If the both hashes are matched, the user will be authenticated and grant permission to requested resources from the server. It is also compatible with proxy servers and it works with firewalls.
To use Digest authentication user needs a browser with Internet Explorer V5.0 or higher. It doesn't support delegation on windows 2000 server. Because of these limitations it is not widely used for authentication purposes.
To implement the Digest authentication select the Digest Authentication for windows domain servers in the Authentication methods window at IIS. (A sample of Authentication methods window is displayed in figure 2). Configure the ASP.NET using Web.config file to use Windows authentication as shown below.





A Dialog box will display to enter credentials when user tries to access the protected site

Figure 5
User will get access for the resources if he/she authenticated. Otherwise an error message will be displayed as shown in Figure 4
Integrated Windows Authentication.

Integrated Windows Authentication will authenticate a user against Windows NT Domain or Active Directory account. This authentication mechanism is very secure because the encrypted password is not sent across the network like in Basic or Digest authentication. It uses either NT LAN Manager (NTLM) or Kerberos authentication.
This authentication is much more suitable for intranet environment that runs behind a fire wall. This schema is not suitable for internet because it only supports windows client. At the same time if user accounts details are stored in external database rather than in a Windows NT domain or Active directory database, this authentication mechanism should not be used for security reasons.
To implement the Integrated Windows authentication select the Integrated Windows Authentication in the Authentication methods window at IIS. (A sample of Authentication methods window is displayed in figure 2). Configure the ASP.NET using Web.config file to use Windows authentication as shown below.





Client Certificate Mapping

A certificate is a digital key in user's computer. When user access a resources from the server this key will be automatically pass in for authentication. User won't have to enter any username and password for authentication. This makes it more attractive option for automated business processes. The client certificates can be mapped to windows accounts or to Active Directory. At the same time developer can implement custom authentication in ASP.NET by using a unique field like email address contained within the certificate.
You need to physically deploy the client certificate to the client machine. At the same time issuing and managing client certificate can be expensive. These are the some of issues that stop using this authentication method widely.
Authenticating an individual user can be done by one-to-one mapping where a certificate is mapped to an individual account. There is no limit of one-to-one mapping if Active directory mapping is used. Many-to-many mapping can be used to authenticate all of the users from particular group or organization.
2. Passport Authentication
Passport authentication is a centralized authorization mechanism provided by Microsoft. It is using a cookie mechanism. This supports a single sign on approach across multiple domains and users will be able to access many passport authentication supported site by single sign on. Because of this the user won't have to input their credentials again and aging to access different passport supported sites. The developers won't be needed to create their own login pages and manage user names and passwords. They simply forward the users to Microsoft passport site for authentication if they haven't authenticated already. When the user get authenticated user will be assign a cookie. This cookie is pass to rest of the passport supported site to get access with out have to enter any credentials.
If you are not interested in maintaining your own user names and pass words database and your site will be used together with other passport supported sites, passport authentication will be perfect for your . Using SSL with Passport authentication can make it more secure.
To implement passport authentication you need to install the Passport SDK on your server and have to register with Microsoft Passport to access their service. At the same time configure web.config file as shown below.





3. Form Authentication
The user will have to pass username and password details directly to the application using HTTP. If the user gets authenticated he/she will be assign with a cookie that will grant access to protected recourse. If the user fails in authentication he/she will be redirected to the login page to enter their username and password. When authenticating the credentials they can be store in a number of ways. Ex: in configuration file, xml file or in a SQL database. The main advantage is it doesn't need a windows account for authentication. To make it more secure we can use SSL when passing the credentials.
To implement the Form authentication the developers will have to create their own login pages and have to manage usernames and passwords. IIS need to be configured allowing Anonymous Authentication. At the same time configure web.config file as shown below.








I won't be going for much details about Form Authentication because I am planning to publishing a article in near future about Form Authentication.
4. None (Custom Authentication)
This will allow to develop custom authentication mechanisms. For a example creating your own authentication schema. It offers the total control of the authentication process and provides great flexibility. But it requires extra work to implement custom authentication schemas.
To implement no authentication or to build your own authentication configure the Web.config file as shown below






Stored Procedure Insert Update Delete

Creating Table
CREATE TABLE employee(
    id          INTEGER NOT NULL PRIMARY KEY,
    first_name  VARCHAR(10),
    last_name   VARCHAR(10),
    salary      DECIMAL(10,2),
    city        VARCHAR(20),   
 )
Now insert some values in the table and using select statement to select a table.
 INSERT INTO employee VALUES (2, 'Monu',  'Rathor',4789,'Agra');
 GO
 INSERT INTO employee VALUES (4, 'Rahul' ,  'Saxena',   5567,'London');
 GO
 INSERT INTO employee VALUES (5, 'prabhat',  'kumar',  4467,'Bombay');
 go
 INSERT INTO employee VALUES (6, 'ramu',  'kksingh',  3456, 'jk');
 go
 select * from employee
Table looks like this.


Figure 1
Stored procedure for Select, insert, update, delete
Here, we create a stored procedure for select,insert,update,delete statements to select the data from the table.
Alter PROCEDURE MasterInsertUpdateDelete
(
    @id         INTEGER,
    @first_name  VARCHAR(10),
    @last_name   VARCHAR(10),
    @salary      DECIMAL(10,2),
    @city        VARCHAR(20), 
    @StatementType nvarchar(20) = ''
)
AS
BEGIN
IF @StatementType = 'Insert'
BEGIN
insert into employee (id,first_name,last_name,salary,city) values( @id, @first_name,  @last_name,  @salary, @city)   
END

IF @StatementType = 'Select'
BEGIN
select * from employee
END 
IF @StatementType = 'Update'
BEGIN
UPDATE employee SET
            First_name =  @first_name, last_name = @last_name, salary = @salary,
            city = @city
      WHERE id = @id
END
else IF @StatementType = 'Delete'
BEGIN
DELETE FROM employee WHERE id = @id
END
end
Now press F5 to execute the stored procedure.
Now open object explorer and select storeprocedure MasterInsertUpdateDelete.
Stored Procedure to Check Insert
StatementType = 'Insert'
MasterInsertUpdateDelete -> right click select execute stored procedure...

Figure2

Execute procedure window will be open.



Figure3
Now for insert we fill the data in required field.
StatementType=insert


Figure4
Click on the ok Button. and check in the employee table with following inserted data.

Figure5
Stored Procedure to Check update
MasterInsertUpdateDelete -> right click select execute stored procedure...
Execute procedure window will be open.
StatementType = 'Update'


Figure6
Click on the ok Button. and check in the employee table with following updated data where id is 7.

Figure7
Stored Procedure to Check Delete
MasterInsertUpdateDelete -> right click select execute stored procedure...
Execute procedure window will be open.
StatementType = 'Delete'


Figure8
we delete record from table which has id=2
Click on the ok Button. and check in the employee table with following deleted data where id is 2.