Wednesday, 22 January 2014

Windows authentication

..............default page.........

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="windows_authentication._default" %>

<!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 runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
 
   <div>
        <div><p>Hello <asp:Label ID="UserLabel" runat="server" Text="Label"></asp:Label></p></div>
        <div><asp:LinkButton ID="SignInAsADifferentUserLinkButton" runat="server" onclick="SignInAsADifferentUserLinkButton_Click">Sign in as a different user</asp:LinkButton></div>
    </div>
    <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/Admin.aspx">AdminPage</asp:HyperLink>
    </form>
</body>
</html>

------------------------------Code Default Page---------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace windows_authentication
{
    public partial class _default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // Show the current logged on user
            UserLabel.Text = Request.LogonUserIdentity.Name;

            // Make sure the browser does not cache this page
            this.DisablePageCaching();
        }

        protected void SignInAsADifferentUserLinkButton_Click(object sender, EventArgs e)
        {
            // Redirect to the "log out" page cq "sign in as a different user" page
            Response.Redirect("AccessdeniedPage.aspx");
        }
        /// <summary>
        /// Make sure the browser does not cache this page
        /// </summary>
        public void DisablePageCaching()
        {
            Response.Expires = 0;
            Response.Cache.SetNoStore();
            Response.AppendHeader("Pragma", "no-cache");
        }

        protected void LinkButton1_Click(object sender, EventArgs e)
        {
           
        }

        protected void lnkSignOut_Click(object sender, EventArgs e)
        {
           
        }
    }
}

--------------------------------------Access denied page design---------------------------

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

<!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 runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </div>
    </form>
</body>
</html>
--------------------------------COde access Denied Page----------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace windows_authentication
{
    public partial class AccessdeniedPage : System.Web.UI.Page
    {

        private int _authenticationAttempts = 0;
        public int AuthenticationAttempts
        {
            get
            {
                if (!string.IsNullOrEmpty(string.Format("{0}", Session["AuthenticationAttempts"])))
                {
                    int.TryParse(Session["AuthenticationAttempts"].ToString(), out _authenticationAttempts);
                }

                return _authenticationAttempts;
            }
            set
            {
                _authenticationAttempts = value;
                Session["AuthenticationAttempts"] = _authenticationAttempts;
            }
        }
        private string _currentUser = string.Empty;
        public string CurrentUser
        {
            get
            {
                _currentUser = Request.LogonUserIdentity.Name;
                Session["CurrentUser"] = _currentUser;
                return _currentUser;
            }
            set
            {
                _currentUser = value;
                Session["CurrentUser"] = _currentUser;
            }
        }
        private string _previousUser = string.Empty;
        public string PreviousUser
        {
            get
            {
                _previousUser = string.Format("{0}", Session["PreviousUser"]);
                return _previousUser;
            }
            set
            {
                _previousUser = value;
                Session["PreviousUser"] = _previousUser;
            }
        }


        protected void Page_Load(object sender, EventArgs e)
        {
         
         


            // Make sure the browser does not cache this page
            this.DisablePageCaching();

            // Increase authentication attempts
            this.AuthenticationAttempts = this.AuthenticationAttempts + 1;


            if (this.AuthenticationAttempts == 1)
            {
                // Change previous user to current user
                this.PreviousUser = this.CurrentUser;

                // Send the first 401 response
               this.Send401();
            }
            else
            {
                // When a browser is set to "automaticaly sign in with current credentials", we have to send two 401 responses to let the browser re-authenticate itself.
                // I don't know how to determine if a browser is set to "automaticaly sign in with current credentials", so two 401 responses are always send when the user
                // does not switch accounts. In Micrososft Office sharepoint the user has to supply the credentials 3 times, when the user does not switch accounts,
                // so it think this is not a problem.
                if (this.AuthenticationAttempts == 2 && this.CurrentUser.Equals(this.PreviousUser))
                {
                    // Send the second 401 response
                   this.Send401();
                 
                }
                else
                {
                    // Clear the session of the current user. This will clear all sessions objects including the "AuthenticationAttempts"
                    Session.Abandon();
                    Session.Clear();

                    // Redirect back to the main page
                    Response.Redirect("default.aspx");
                }
            }
        }

        /// <summary>
        /// Make sure the browser does not cache this page
        /// </summary>
        public void DisablePageCaching()
        {
            Response.Expires = 0;
            Response.Cache.SetNoStore();
            Response.AppendHeader("Pragma", "no-cache");
        }
        /// <summary>
        /// Send a 401 response
        /// </summary>
        public void Send401()
        {
            // Create a 401 response, the browser will show the log-in dialogbox, asking the user to supply new credentials,
            // if browser is not set to "automaticaly sign in with current credentials"
            Response.Buffer = true;
            Response.StatusCode = 401;
            Response.StatusDescription = "Unauthorized";

            // A authentication header must be supplied. This header can be changed to Negotiate when using keberos authentication
            Response.AddHeader("WWW-Authenticate", "NTLM");

            // Send the 401 response
            Response.End();
        }
    }
        }
   
-----------------------------web.config-------------------------
<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
    <connectionStrings>
        <add name="DBtestmailConnectionString" connectionString="Data Source=LHR-MH-PC79\;Initial Catalog=DBtestmail;Integrated Security=True"
            providerName="System.Data.SqlClient" />
    </connectionStrings>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
   
        <authentication mode="Windows"/>
        <identity impersonate="false" />
        <authorization>
       
          <deny users="?"/>
        </authorization>
      <anonymousIdentification enabled="false"/>
    </system.web>

  <location path="Admin.aspx">
    <system.web>
      <authorization>
     
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>
  <location path="user.aspx">
    <system.web>
      <authorization>

        <deny users="?"/>
      </authorization>
    </system.web>
  </location>

</configuration>
------------------------------------------Global.axps for returning to default not showing error--------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

namespace windows_authentication
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {

        }

        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_EndRequest(Object sender, EventArgs e)
        {
                if (HttpContext.Current.Response.Status.StartsWith("401"))
                    {
                        HttpContext.Current.Response.ClearContent();
                            Server.Execute("default.aspx");
                        }
                        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}

No comments:

Post a Comment