Forms Authentication Basics

Introduction

Authentication is the process of determining whether someone or something is, in fact, who or what it is declared to be. In General authentication is done using Logon methods. We are going to have a look at general authentication mechanism used in web application, Forms authentication. This is one of the most commonly used form of authentication for web applications.

Topics

  • Basics of Form Authentication
  • Design
  • Custom Authentication
  • Authenticate Request
  • Authorize Action Filter

Basics of Form Authentication

To enable forms authentication make sure that, application has proper configurations enabled.

  <system.web>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Index" timeout="2880" />
    </authentication>
  </system.web>

Identity

Basic forms authentication discussed here authorizes user on whose behalf the code is running. Read more about IIdentity here.

Forms Authentication Ticket

This ticket is used to store data required to authenticate user. Read more here.

Form Authentication

FormsAuthentication is used as service to manage all web authentication request. Read more here

Design

  • ICustomAuthentication Interface will authenticate user and create custom authentication principal.
  •  public interface ICustomAuthentication
     {
         void Authenticate(string username, string password);
         void CreateCustomPrincipal();
     }
    
  • IDataService Interface will take care of interacting with database to validate the current user information with details stored in the system/database.
  •  public interface IDataService
     {
        bool CheckCredentials(string username, string password)
     }
    

Custom Authentication

Below is a sample implementation of custom authentication interface described above.

Authenticate

This method takes username and password as input and checks for the validity of credentials. If its valid, a forms authentication cookie is created and encrypted and assigned to HttpContext.

CreateCustomPrincipal

Once the user is authenticated and the authentication cookie is created, current User is set to a generic/custom Prinicpal created out of IIdentity Interface.

public class SecurityServices : Interfaces.Security.ICustomAuthentication
{
        public void Authenticate(string username, string password)
        {
            DataServices ds = new DataServices();

            if (!ds.CheckCredentials(username, password))
                return;

            var authTicket = new FormsAuthenticationTicket(1, username, DateTime.Now,
                                               DateTime.Now.AddSeconds(30), true, "");

            string cookieContents = FormsAuthentication.Encrypt(authTicket);

            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieContents)
            {
                Expires = authTicket.Expiration,
                Path = FormsAuthentication.FormsCookiePath
            };

            if (HttpContext.Current != null)
            {
                HttpContext.Current.Response.Cookies.Add(cookie);
            }

            return;
        }

        public void CreateCustomPrincipal()
        {
            HttpCookie authCookie =   HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
            if (authCookie != null)
            {
                FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                var identity = new GenericIdentity(authTicket.Name, "Forms");
                var principal = new CustomPrincipal(identity);
                HttpContext.Current.User = principal;
            }
         }
 }

CustomPrincipal

Custom principal will contain the role validation and the authentication status for the current user, this is an extension of IPrincipal.

public class CustomPrincipal : IPrincipal
{
        public CustomPrincipal(IIdentity identity)
        {
            Identity = identity;
        }

        public bool IsInRole(string role)
        {
            if (String.Compare(role, "admin", true) == 0)
            {
                return (Identity.Name == "admin");
            }
            else
            {
                return false;
            }
        }

        public IIdentity Identity
        {
            get;
            private set;
        }
}

Authenticate Request

In this example, Http pipeline is used to authenticate the request. To add a new http module to the current pipeline, add below configuration. Make sure that Type and dll is updated properly.

<system.web>
  <httpModules>
     <add name="SecurityAuthModule" 
          type="WebSecurity.Pipeline.HttpSecurityPipeline, WebSecurity"/>
  </httpModules>
</system.web>

Authorize request will be invoked by Http module on AuthenticateRequest as shown below.

public class HttpSecurityPipeline : IHttpModule
{
        public void Dispose()
        {
            throw new NotImplementedException();
        }

        public void Init(HttpApplication context)
        {
            context.AuthenticateRequest += new EventHandler(this.ApplicationAuthRequest);
        }

        protected void ApplicationAuthRequest(object sender, EventArgs args)
        {
            new WebSecurity.SecurityServices().CreateCustomPrincipal();
        }
}

Authorize Request

When you mark an action method with AuthorizeAttribute, access to that action method is restricted to users who are both authenticated and authorized. If you mark a controller with the attribute, all action methods in the controller are restricted. Read more here.

[Authorize]
public class HomeController : Controller
{
        //
        // GET: /Home/
        public ActionResult Index()
        {
            ViewData.Add(new KeyValuePair<string, object>("User", User.Identity.Name));
            return View();
        }
}

How to Use Simple Authentication

    public class AccountController : Controller
    {
        //
        // GET: /Account/
        [AllowAnonymous]
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login()
        {
            new WebSecurity.SecurityServices().Authenticate("UserName", "password");
            return RedirectToAction("Index", "Home");
        }
    }

Download Project Source code

Advertisements

2 thoughts on “Forms Authentication Basics

  1. Thanks for your post! It was the simplest and easiest I could find. Somehow the ‘logout’ is not working here but it’s still a great tutorial. Thank you!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s