Mixed Authentication In ASP.NET

If you want an intranet application to authenticate itself from the windows credentials when accessed internally and ask for a username and password when accessed over the internet , then you should be following Mixed Authentication.

To get this working -

In Web.Config-

<authentication mode="Forms">
<forms loginUrl="WinLogin.aspx" defaultUrl="Default.aspx" name="authCookie" timeout="240" path="/">
</forms>
</authentication>





where WinLogin.aspx is just a dummy page without any markup and the following code-



IServiceProvider service = (IServiceProvider)this.Context;
HttpWorkerRequest request = (HttpWorkerRequest)service.GetService(typeof(HttpWorkerRequest));
this.Response.Cookies.Add(new HttpCookie("UserToken", request.GetUserToken().ToString()));
string userName = this.Request.ServerVariables["LOGON_USER"];
FormsAuthentication.RedirectFromLoginPage(userName, true);





Then in Global.asax File -



void Application_AuthenticateRequest(object sender, EventArgs e)
{
// Extract the forms authentication cookie
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];

if (null == authCookie)
{
// There is no authentication cookie.
return;
}

FormsAuthenticationTicket authTicket = null;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch (Exception ex)
{
// Log exception details (omitted for simplicity)
return;
}

if (null == authTicket)
{
// Cookie failed to decrypt.
return;
}
else if(null != authTicket)
{

// When the ticket was created, the UserData property was assigned a
// pipe delimited string of role names.
string[] roles = authTicket.UserData.Split(new char[] { '' });

// Create an Identity object
//FormsIdentity id = new FormsIdentity(authTicket);
System.Security.Principal.GenericIdentity id = new System.Security.Principal.GenericIdentity(authTicket.Name, "LdapAuthentication");

// This principal will flow throughout the request.
System.Security.Principal.GenericPrincipal principal = new System.Security.Principal.GenericPrincipal(id, roles);
// Attach the new principal object to the current HttpContext object
Context.User = principal;
}
if (this.Request.Cookies["UserToken"] != null)
{
string token = this.Request.Cookies["UserToken"].Value;
IntPtr userToken = new IntPtr(int.Parse(token));
System.Security.Principal.WindowsIdentity identity = new System.Security.Principal.WindowsIdentity(userToken, "NTLM", System.Security.Principal.WindowsAccountType.Normal, true);
HttpContext.Current.User = new System.Security.Principal.WindowsPrincipal(identity);
}
}





Finally in every Page_Load check for this condition-



if (Context.User.Identity.AuthenticationType == "NTLM")





Hope this helps





Cheers

0 Responses to "Mixed Authentication In ASP.NET"

Post a Comment