Thursday, October 15, 2015

Authentication-Authorization / Windows built-in Role enumeration

In web.config file you will get following
<system.web>
          <authentication mode="Windows/Form/Passport/None">
          </authentication>
</system.web>
Windows: Is used togther with IIS authentication, where authentication is perform in the following ways: Basic,digest or integrated windows.

Form: Request that are not authenticated are redirected to an HTML form

Passport: A centrilized authentication service provided by the microsoft that offers single login and core profile services for member site.
In this tutorial my focus will be on Form-Based Authentication: this type of authentication will have following web.config file.
<system.web>
          <authentication mode="Forms">
                   <forms name="FrmLogin" loginUrl="./Login.aspx" path="/"> </forms>
          </authentication>
          <authorization>
                   <deny users="?"/>
          </authorization>
</system.web>
Here loginURL attribute points to the page that contain the applications login page and
attribute path specifies location to which cookies get stored as users access token.

Checking credentials against SQL Server
Here is login.aspx code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td colspan="2">User Authentication</td>
            </tr>
            <tr>
                <td>Login Name:</td>
                <td><asp:TextBox ID="txtLoginName" runat="server"></asp:TextBox></td>
            </tr>
            <tr>
                <td>Password:</td>
                <td><asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox></td>
            </tr>
            <tr>
                <td style="height: 26px"></td>
                <td style="height: 26px"><asp:Button ID="btnLogin" runat="server"OnClick="btnLogin_Click" Text="Login Me" /></td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"ControlToValidate="txtLoginName"
                        Display="Dynamic" ErrorMessage="Login name is required"></asp:RequiredFieldValidator>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"ControlToValidate="txtPassword"
                        Display="Dynamic" ErrorMessage="Password is required"></asp:RequiredFieldValidator></td>
            </tr>
        </table>   
    </div>
        <asp:Label ID="lblMessage" runat="server" ForeColor="Red"></asp:Label>
    </form>
</body>
</html>
Here is code behind code
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        SqlConnection SqlCon = newSqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
        string strSql = "SELECT UserName, UserPassword FROM Tbl_Login WHERE UserName='" + txtLoginName.Text.Replace("'""") + "' AND UserPassword='" + txtPassword.Text.Replace("'""") + "'";
        SqlCommand SqlComd = new SqlCommand(strSql, SqlCon);
        SqlDataReader sqlRdr;
        try
        {
            SqlCon.Open();
            sqlRdr = SqlComd.ExecuteReader(CommandBehavior.CloseConnection);
            if (sqlRdr.Read())
            {
                FormsAuthentication.RedirectFromLoginPage(txtLoginName.Text, true);
            }
            else
            {
                lblMessage.Text = "Invalid credential supplied!";
            }
        }
        catch (Exception ex)
        {
            lblMessage.Text = ex.Message;
        }
        finally
        {
            //SqlCon.Close();
        }
    }
}
You can use SignOut() method as
On default.aspx/cs page I have used signout functionality as
protected void DoLogout(object sender, EventArgs e)
{
    FormsAuthentication.SignOut();
    Response.Redirect("./Login.aspx");
}
If you are using Windows authentication you can use WindowsIdentity object and other objects. To have access to these richer objects you should use System.Security.Principle which uses role from the WindowsBuiltInRole enumeration, which has following roles.
  1. AccountOperator
  2. Administrator
  3. BackupOperator
  4. Guest
  5. PowereUser
  6. PrintOperator
  7. Replicator
  8. SystemOperator
  9. Users
On seperate page you can have code as
protected void Page_Load(object sender, EventArgs e)
{
    WindowsIdentity LgnUser = new WindowsIdentity("Administrator");
    Response.Write("Authenticatio Type:" + LgnUser.AuthenticationType.ToString() + "<br>");
    Response.Write("Impersonate Level:" + LgnUser.ImpersonationLevel.ToString() + "<br>");
    Response.Write("Is Guest:" + LgnUser.IsGuest + "<br>");
    Response.Write("Is Authenticated:" + LgnUser.IsAuthenticated.ToString());
    Response.Write("Name:" + LgnUser.Name.ToString());
}

You can print the current identity details. For this you might need to change trust level.

No comments:

Post a Comment