Free Web Development Online Tutorials, Learn to Code
Learn Asp.net Aspx, Free Asp.net Tutorial in C#, Asp.net Web Application Development Guide

Asp.net Authentication and Authorization Example

What is Authentication in ASP.NET?

Authentication is a mechanism to check if user has right to access the application data, so it asks for some credentials like username and password and check with database before allowing user to enter in secure area of application.

Authentication is the security aspect of any application, event after checking Authentication there is another security check known as “Authorization”, to confirm for which are the areas user has access right.

So you must know what is Authorization !
Authorization is the process of setting access rights for authenticated user, it says which are the resources that particular user can access, and what type of access.

While talking about Authentication in Asp.Net Application, we must remember the Life cycle of Application.
There are two separate authentication layers, first is IIS and then Asp.Net. All web requests will flow through IIS before they are handed over to ASP.net. So IIS can decide to accept or deny access without telling the ASP.net processor that someone requested a particular page

  1. When any web page request received, IIS first checks to make sure the if incoming request is allowed access to the domain. If not it denies the request
  2. By default IIS allows anonymous access, that means any incoming requests are automatically authenticated, but we can configure to make sure we allow request to processed further if received from authenticated user.
  3. When ASP.net received the request, it checks to see whether impersonation is enabled

In Asp.Net there are different Authentication Modes

<authentication mode="windows">
<authentication mode="passport">
<authentication mode="forms">
Custom Authentication in Asp.net

In this tutorial we learn how to implement custom Authentication, Receiving user input from web form and then calling data access layer and finally checking data with database.

asp.net authentication check

So in example we do following things

  1. Create a asp.net form to receive credentials from user
  2. In code behind we write a method that will receive the user data and check with database
  3. If authenticated, it will redirect user to secure pages, if not then it will show some failure messages to user on same page.
<table style="width: 100%;" border="0"> <tr> <td align="right">
Username </td>
<td align="left">
<asp:TextBox runat="server" ID="txtUsername" CssClass="txtBox" Width="220px"> </asp:TextBox>
<asp:RequiredFieldValidator ID="rfvUsername" runat="server" Display="None" ErrorMessage="Provide user name."
ControlToValidate="txtUsername"> </asp:RequiredFieldValidator> </td> </tr> <tr>
<td align="right">
Password
</td>
<td align="left">
<asp:TextBox ID="txtPassword" runat="server" CssClass="txtBox" Width="220px" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvPassword" runat="server" Display="None" ErrorMessage="Provide password."
ControlToValidate="txtPassword"> </asp:RequiredFieldValidator>                
</td>                            
</tr>                        
<tr> 
<td colspan="3">
<asp:Button ID="btnSubmit" runat="server" Text="Sign in" CssClass="button" OnClick="btnSubmit_Click" />
</td>
</tr>
</table>

asp.net authentication


Now let's look at the code behind how we can check user input with the data stored in database

protected void btnSubmit_Click(object sender, EventArgs e)
{
tbUserInfo user = null;
         
    using (SecurityDTO dto = new SecurityDTO())
    {
        user = dto.Authenticate(EncryptUtil.Encrypt(txtUsername.Text), EncryptUtil.Encrypt(txtPassword.Text));
        Session[SessionKeys.User] = user;
    }
    if (user != null)
    {
        switch (user.UserTypeId)
        {
            case 1: // System Admin
                Response.Redirect("~/Secure/SysAdmin/");
                break;
            case 2: // Production Manager
                Response.Redirect("~/Secure/Default.aspx");
                break;
            case 3: // Merchandiser
                Response.Redirect("~/Secure/Merchandise/");
                break;
            case 4: // Trade Manager
                Response.Redirect("~/Secure/Trade/");
                break;
            case 5: // Marketing Manager
                Response.Redirect("~/Secure/Inventory");
                break;
            case 6: // HR manager
                Response.Redirect("~/Secure/HR/");
                break;
            case 7: // Quality Analyst
                Response.Redirect("~/Secure/Default.aspx");
                break;
            case 8: // Quality Analyst
                Response.Redirect("~/Secure/Acct");
                break;
        }
    }
    else
        labMessage.Text = "Authentication Failed!";         
}

Now we create a Data Transfer Class (considered as middle layer) where we compare the data we received from presentation layer with data stored in database

If we find data match then return a UserInfo ( in this example tbUserInfo) object with user information.

public class SecurityDTO
{
public tbUserInfo Authenticate(string userName, string password)
{
tbUserInfo userinfo = null;
using (ETGJewelryEntities context = new ETGJewelryEntities())
{
userinfo = context.tbUserInfoes
.Where(uv =>
uv.UserName == userName &&
uv.Password == password &&
uv.IsActive == true)
.FirstOrDefault<tbUserInfo>();
if (userinfo != null)
{
userinfo.UserRole = context.tbUserRoles
.Where(u => u.UserId == userinfo.UserId)
                .ToList<tbUserRole>();
            }                
        }
    return userinfo;
    }		
}

Now if you notice in UserInfo class there is a UserRole property, any user can have single or multiple roles; based on their role type they will have access to different resources inside the application .


Comment
Name
Email
Website
Subscribe
 
How to check Authentication in Asp.net, check authorization