Home > DeveloperSection > Articles > Security in ASP.NET

Security in ASP.NET


.NET C#  ASP.Net  Security in .Net  Authentication  Authorization 
Ratings:
0 Comment(s)
 1571  View(s)
Rate this:

Security in ASP.NET

 In this article, I’m explaining about Security in .NET

Authentication:

It is the process of ensuring the user’s identity and authenticity ASP.NET allows four types of mode:

1.      Windows(Default)

2.      Forms

3.      Passport

4.      None

 

Windows:

 The window authentication provider allows you to authenticate users based on their window accounts. This provider uses IIS to perform the actual authentication and then passes the authenticated identity to your code. This is the default provider for ASP.NET.

Forms:

The forms authentication provider uses custom HTML forms to collect authentication information and allows you to use you own logic to authenticate users. The user’s credentials are then stored in a cookie for use during the session.

 

Passport:

The passport authentication provider uses Microsoft’s passport service to authenticate users. Passport is a forms-based authentication service.

 

None (Custom):

Specify “None” as the authentication provider when users are not authenticated at all or if you plan to develop custom authentication code.

 

Federated Identity:

 

It refers to where the user stores their credentials. Alternatively, FID can be viewed as a way to connect Identity Management systems together. In FID, a user's credentials are always stored with the "home" organization (the "identity provider"). When the user logs into a service, instead of providing credentials to the service provider, the service provider trusts the identity provider to validate the credentials. So the user never provides credentials directly to anybody but the identity provider.

 

Authorization

Authorization is a process by which a server determines if the client has permission to use a resource or access a file.

<authorization>

     <allow roles ="Admin"/>

      <deny users ="*"/>

</authorization>

           

Membership

The membership feature is built around two central classes:

1.      Membership

2.       MembershipUser.

The membership class provides methods for creating users (represented by the MembershipUser class), as well as common administration methods for managing users. The users that are created with the membership class represent the authenticated identities for an ASP.NET application. The key class in the Membership framework is the membership class, which has methods like:

1.      CreateUser

2.      DeleteUser

3.      GetAllUsers

4.      UpdateUser

5.      ValidateUser

Example:

 <membership defaultProvider="Demo_MemberShipProvider">

      <providers>

        <add connectionStringName="cnn" enablePasswordRetrieval="false"

         enablePasswordReset="true" requiresQuestionAndAnswer="true" applicationName="/"

         requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="5"

         minRequiredPasswordLength="5" minRequiredNonalphanumericCharacters="0"

         passwordAttemptWindow="10" passwordStrengthRegularExpression=""

         name="Demo_MemberShipProvider" type="System.Web.Security.SqlMembershipProvider" />

      </providers>

    </membership>

 

Role Manager

The central management class for role Manager is the Roles class. The Roles class provider methods for creating roles and assigning users to roles. It also provides common administration methods for managing role information.

<roleManager enabled="true" cacheRolesInCookie="true" cookieName="DemoRoles" defaultProvider="SqlProvider">

      <providers>

        <add connectionStringName="cnn" applicationName="/" name="SqlProvider"

         type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

      </providers>

    </roleManager>

 

Create a LoginForm

Login.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="login1.aspx.cs" Inherits="AuthenticationApplication.login1" %>

 

<!DOCTYPE html>

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

 

        <div>

            <h3><a href ="RegistrationFile.aspx" id ="login" runat ="server">New Registration</a></h3>

        </div>

        <asp:Login ID="Login1" runat="server" OnAuthenticate="Login1_Authenticate" >

 

        </asp:Login>

    </div>

    </form>

</body>

</html>

 

Login.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.Security;

namespace AuthenticationApplication

{

    public partial class login1 : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            if (User.Identity.IsAuthenticated)

            {

                Response.Redirect("HomePage.aspx");

            }

        }

 

        protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)

        {

       

            if (Membership.ValidateUser(Login1.UserName, Login1.Password) == true)

            {

              FormsAuthentication.RedirectFromLoginPage(Login1.UserName, true);

            }

            else

                Response.Write("Invalid login");

      }

    }

}

Registration.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="RegistrationFile.aspx.cs" Inherits="AuthenticationApplication.RegistrationFile" %>

 <!DOCTYPE html>

 <html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

     <asp:CreateUserWizard ID="CreateUserWizard1" runat="server" OnContinueButtonClick="CreateUserWizard1_ContinueButtonClick" OnCreatedUser="CreateUserWizard1_CreatedUser">

            <WizardSteps>

                <asp:CreateUserWizardStep ID="CreateUserWizardStep1" runat="server">

                </asp:CreateUserWizardStep>

                <asp:CompleteWizardStep ID="CompleteWizardStep1" runat="server">

                </asp:CompleteWizardStep>

            </WizardSteps>

        </asp:CreateUserWizard>

    </form>

</body>

</html>

RegistrationForm.aspx.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.Security;

namespace AuthenticationApplication

{

    public partial class RegistrationFile : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

 

        }

 

        protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)

        {

            MembershipCreateStatus status;

            Membership.CreateUser(CreateUserWizard1.UserName, CreateUserWizard1.Password, CreateUserWizard1.Email, CreateUserWizard1.Question, CreateUserWizard1.Answer, true, out status);

            if (Roles.RoleExists("Admin"))

            {

                Roles.AddUserToRole(CreateUserWizard1.UserName, "Admin");

            }

            else

            {

                Roles.CreateRole("Admin");

                Roles.AddUserToRole(CreateUserWizard1.UserName, "Admin");

            }

        }

 

        protected void CreateUserWizard1_ContinueButtonClick(object sender, EventArgs e)

        {

            Response.Redirect("login1.aspx");

        }

    }

}

Create a MasterPage.Master

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="MasterPage.master.cs" Inherits="AuthenticationApplication.MasterPage" %>

 

<!DOCTYPE html>

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

    <asp:ContentPlaceHolder ID="head" runat="server">

    </asp:ContentPlaceHolder>

</head>

<body>

    <form id="form1" runat="server">

        <div>

               <div style="float:right">

                 <asp:Button ID="btnlogin" runat="server" Text="login" OnClick="btnlogin_Click"  />

                </div>

        </div>

    <div>

        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server" OnPreRender="ContentPlaceHolder1_PreRender">

       

        </asp:ContentPlaceHolder>

    </div>

    </form>

</body>

</html>

Create MasterPage.Master.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.Security;

using System.Security.Principal;

namespace AuthenticationApplication

{

    public partial class MasterPage : System.Web.UI.MasterPage

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            if (this.Context.User.Identity.Name != null)

            {

                btnlogin.Text = "logout";

            }

          

        }

 

        protected void btnlogin_Click(object sender, EventArgs e)

        {

            if (this.Context.User.Identity.Name != null)

            {

                FormsAuthentication.SignOut();

                btnlogin.Text = "login";

                Response.Redirect("~/login1.aspx");

            }

          

        }

 

        protected void ContentPlaceHolder1_PreRender(object sender, EventArgs e)

        {

          

        }

 

    }

}

Create HomePage.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true" CodeBehind="HomePage.aspx.cs" Inherits="AuthenticationApplication.HomePage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

    WelCome home page

</asp:Content>

 

Create  Global.asax.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.SessionState;

 

namespace AuthenticationApplication

{

    public class Global : System.Web.HttpApplication

    {

 

        protected void Application_Start(object sender, EventArgs e)

        {

            if (User!=null &&!User.Identity.IsAuthenticated)

                Response.Redirect("login1.aspx");

        }

 

        protected void Session_Start(object sender, EventArgs e)

        {

 

        }

 

        protected void Application_BeginRequest(object sender, EventArgs e)

        {

           

             

        }

 

        protected void Application_AuthenticateRequest(object sender, EventArgs e)

        {

 

        }

 

        protected void Application_Error(object sender, EventArgs e)

        {

 

        }

 

        protected void Session_End(object sender, EventArgs e)

        { 

        }

 

        protected void Application_End(object sender, EventArgs e)

        {

            FormsAuthentication.SignOut();

        }

    }

}

 

 

Create an Admin Folder

Add an Admin.aspx file

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true" CodeBehind="Admin.aspx.cs" Inherits="AuthenticationApplication.Admin.Admin" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

    <div style="float:right">

        </div>

    <div style ="height:450px;">

<h2>Admin Panel:</h2>

<table>

<tr>

<td>

    <asp:TextBox ID="txtrolename" runat="server"></asp:TextBox>

    <asp:Button ID="btnCreateRole" runat="server" Text="CreateRole" OnClick="btnCreateRole_Click"/>

</td>

</tr>

<tr>

<td>

<table>

<tr>

<td>Available Users</td>

<td>Available Roles</td>

</tr>

<tr>

<td style="height: 72px">

    <asp:ListBox ID="lstusers" runat="server" Height="95px" Width="105px"></asp:ListBox>

</td>

<td style="height: 72px">

    <asp:ListBox ID="lstRoles" runat="server" Height="92px" Width="95px"></asp:ListBox>

</td>

</tr>

</table>

</td>

</tr>

<tr>

<td>

    <asp:Button ID="btnAssignRoleToUser" runat="server" Text="Assign Role To User" Width="175px" OnClick="btnAssignRoleToUser_Click" />

</td>

</tr>

<tr>

<td>

    <asp:Button ID="btnRemoveUserFromUser" runat="server" Text="Remove User From Role" OnClick="btnRemoveUserFromUser_Click" />

   

</td>

</tr>

<tr>

<td>

    <asp:Button ID="btnRemoveRoles" runat="server" Text="Delete Roles" Width="176px" OnClick="btnRemoveRoles_Click" style="height: 26px" />

</td>

</tr>

<tr>

<td>

    <asp:Label ID="Label1" runat="server"></asp:Label>

</td>

</tr>

</table>

</div>

       

</asp:Content>

 

Write Admin.aspx.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

using System.Web.Security;

 

namespace AuthenticationApplication.Admin

{

    public partial class Admin : System.Web.UI.Page

    {

        SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["cnn"].ConnectionString);

        protected void Page_Load(object sender, EventArgs e)

        {

 

            if (!IsPostBack)

            {

                BindRoles();

                BindUsers();

                Label1.Text = "";

            }

 

        }

        public void BindRoles()

        {

            SqlDataAdapter sda = new SqlDataAdapter("select RoleName from aspnet_Roles", cnn);

            DataSet ds = new DataSet();

            sda.Fill(ds, "Roles");

            lstRoles.DataSource = ds;

            lstRoles.DataTextField = "RoleName";

            lstRoles.DataTextField = "RoleName";

            lstRoles.DataBind();

        }

        public void BindUsers()

        {

            SqlDataAdapter da = new SqlDataAdapter("select UserName from aspnet_users", cnn);

            DataSet ds = new DataSet();

            da.Fill(ds, "Roles");

            lstusers.DataSource = ds;

            lstusers.DataTextField = "UserName";

            lstRoles.DataValueField = "RoleName";

            lstusers.DataBind();

        }

 

        protected void btnAssignRoleToUser_Click(object sender, EventArgs e)

        {

            Label1.Text = "";

            try

            {

                if (!Roles.IsUserInRole(lstRoles.SelectedItem.Text))

                {

                    Roles.AddUserToRole(lstusers.SelectedItem.Text, lstRoles.SelectedItem.Text);

                    BindUsers();

                    BindRoles();

                    Label1.Text = "User Assigned To User Successfully";

                }

                else

                {

                    Label1.Text = "Role(s) Already Assigned To User";

                }

            }

            catch (Exception ex)

            {

                Label1.Text = ex.Message;

            }

        }

 

        protected void btnRemoveUserFromUser_Click(object sender, EventArgs e)

        {

            Label1.Text = "";

            try

            {

                Roles.RemoveUserFromRole(lstusers.SelectedItem.Text, lstRoles.SelectedItem.Text);

                BindUsers();

                BindRoles();

                Label1.Text = "Role(s) Removed Successfully";

            }

            catch (Exception ex)

            {

                Label1.Text = ex.Message;

            }

        }

 

        protected void btnRemoveRoles_Click(object sender, EventArgs e)

        {

            Label1.Text = "";

            try

            {

                Roles.DeleteRole(lstRoles.SelectedItem.Text);

                BindUsers();

                BindRoles();

                Label1.Text = "Role(s) Removed Successfully";

            }

            catch (Exception ex)

            {

                Label1.Text = ex.Message;

            }

        }

 

        protected void btnCreateRole_Click(object sender, EventArgs e)

        {

            Label1.Text = "";

            try

            {

                if (!Roles.RoleExists(txtrolename.Text))

                {

                    Roles.CreateRole(txtrolename.Text);

                    BindUsers();

                    BindRoles();

                    Label1.Text = "Role(s) Created Successfully";

                }

                else

                {

                    Label1.Text = "Role(s) Already Exists";

                }

            }

            catch (Exception ex)

            {

                Label1.Text = ex.Message;

            }

        }

}

 

Add in web.config file in Admin folder

<?xml version="1.0"?>

<configuration>

  <appSettings/>

  <connectionStrings/>

      <system.web>

        <authorization>

        <allow roles ="Admin"/>

        <deny users ="*"/>

      </authorization>

    </system.web>

 </configuration>

 

 

Write in application web.config file

<?xml version="1.0"?>

<configuration>

  <appSettings>

    <add key="ValidationSettings:UnobtrusiveValidationMode" value="None"/>

  </appSettings>

  <connectionStrings>

    <add name="cnn" connectionString="Data Source=YourServerName;Initial Catalog=PriyankaDB; User Id=UserID;Password=UserPassword;" providerName="System.Data.SqlClient"/>

  </connectionStrings>

 

  <system.web>

    <authentication mode="Forms">

      <forms cookieless="UseCookies" defaultUrl="HomePage.aspx" loginUrl="login1.aspx" protection="All" timeout="30"></forms>

    </authentication>

    <membership defaultProvider="Demo_MemberShipProvider">

      <providers>

        <add connectionStringName="cnn" enablePasswordRetrieval="false"

         enablePasswordReset="true" requiresQuestionAndAnswer="true" applicationName="/"

         requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="5"

         minRequiredPasswordLength="5" minRequiredNonalphanumericCharacters="0"

         passwordAttemptWindow="10" passwordStrengthRegularExpression=""

         name="Demo_MemberShipProvider" type="System.Web.Security.SqlMembershipProvider" />

      </providers>

    </membership>

      <compilation debug="true" targetFramework="4.5" />

      <httpRuntime targetFramework="4.5" />

    <roleManager enabled="true" cacheRolesInCookie="true" cookieName="DemoRoles" defaultProvider="SqlProvider">

      <providers>

        <add connectionStringName="cnn" applicationName="/" name="SqlProvider"

         type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

      </providers>

    </roleManager>

    </system.web>

  <location path="Registration.aspx">

    <system.web>

      <authorization>

        <allow users="*"/>

      </authorization>

    </system.web>

  </location>

 

</configuration>

 

 

Output:

Registrationform.aspx


Admin form access only Admin User


Don't want to miss updates? Please click the below button!

Follow MindStick