Custom Authentication and Basic understanding
Custom authentication allows to write our own module and set page user(httpcontext.user)
Custom Authentication
Problem Scenario
How does custom authentication Work
Little understanding on authentication
Asp.net worker process uses many httpmodules to perform different types of authentications.Correct httpmodule is loaded based on web.config entry. By default there are three httpmodules in machine.config file. Please see the following default entries in machine .config file.
These authentication modules are responsible for creating IPrincipal object and storing it in the HttpContext.User property. This propery is used to take authroization decision.
What all are required to make custom authentication work
step 1: Write our own http module and hook custom handler to AuthenticateRequest event.
step 2: Create an IPrincipal object and store in HttpContext.User property.Createing IPrincipal object is provides developer flexibility to change asp.net page user(httpcontext.user) based on business rule.
step 3: Web.config entry for custom httpmodule.
step 4 : write your own httpmodule.
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Security.Principal;
///
/// Summary description for CustomWindowsAuthentication
///
public class CustomAuthentication : IHttpModule
{
private HttpApplication httpApp;
public void Init(HttpApplication httpApp)
{
this.httpApp = httpApp;
//httpApp.AuthenticateRequest += new EventHandler(OnAuthentication);
}
void OnAuthentication(object sender, EventArgs a)
{
string UserName = string.Empty;
HttpContext httpContext = null;
try
{
Context = HttpContext.Current;
UserName = Context.User.Identity.Name;
// TODO:
//UserName =
// Write some business logic to authenticate user against your application or what ever else required.
if (!string.IsNullOrEmpty(UserName))
{
System.Security.Principal.IIdentity customIdentity = new System.Security.Principal.GenericIdentity(UserName);
System.Security.Principal.IPrincipal customPrincipal = new System.Security.Principal.GenericPrincipal(customIdentity, null);
HttpContext.Current.User = customPrincipal;
}
}
catch (System.Threading.ThreadAbortException)
{
// Exception Handling
}
catch (Exception exp)
{
// Exception Handling
}
}
public void Dispose()
{ }
}