Single Sign-On (SSO) implementation in ASP.NET MVC

To start with any secured web application, the developer needs to work on the implementation of the authentication functionality. If any user needs to enter into multiple secured web application on the same domain in the .NET framework, he needs to log-in through each of those applications. Logging in a number of times can be avoided with Single Sign On (SSO) functionality.

SSO is a functionality that allows to login once and accesses multiple web applications with the same credentials.

For example – once the user enters a user name and password on Gmail, he will be able to access Google’s other web application like Google Plus, YouTube, Play store, etc., with same credentials without logging in again.


HOW SSO WORKS:
When a user runs a page in an application that requires user-based authentication, the application searches for a cookie (forms authentication cookie) in the HTTP request, if it does not find the cookie, it redirects the current page to the login page.
The user enters valid credentials and clicks “Login” button, the system validates the credentials in data storage and set the credentials in Thread.CurrentPrincipal.Identity.Name property in .NET framework, and create a cookie in Response, and redirects to the requested page.
If a user navigates to another page of the application, the browser sends the authentication cookie as it already has the cookie from the last response. The browser when gets the cookie validates the cookie properties; if the cookie is not expired, then the browser will fetch the required information from the cookie and set the user name into the Thread.CurrentPrincipal.Identity.Name property in .NET framework.

IMPLEMENT SSO IN MVC:

Here we see the steps to implement SSO in MVC Application using .NET
  1. Open visual studio, create three blank applications (SingleSignOn, ApplciationA & ApplicationB). SingleSignOn application is for login functionality and ApplicationA and ApplicationB are secured web applications.
  2. The solution will look something like below:

  3. Add an AccountController in SingleSignOn, It will contain the login functionality code.


  4. Write login code or simple forms authentication code in the AccountController as below:
    public class AccountController : Controller
        {
            // GET: Accountpublic 
            ActionResult Login(string returnUrl)
            {
                if (Request.IsAuthenticated)
                {
                    return RedirectToAction("Index", "Home");
                }
                ViewBag.ReturnUrl = returnUrl; return View();
            }
            [AllowAnonymous]
            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Login(string userName, string password, string returnUrl)
            {
                if (FormsAuthentication.Authenticate(userName, password))
                {
                    FormsAuthentication.SetAuthCookie(userName, false);
                    if (!string.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid Login Detials");
                    ViewBag.ReturnUrl = returnUrl; return View();
                }
            }
        }
    FormsAuthentication.Authenticate method will check the credentials and authenticate whether user name and password are correct or not. We can also validate username and password from the SQL Server database or from any other Data Source.
  5. Now we will add a login view and write HTML form in the login view for user login.
    @using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl }))
    {
        @Html.ValidationSummary()
        @Html.AntiForgeryToken()
        @Html.Label("UserName  @Html.Editor("UserName")
        @Html.LabelForModel("Password")
        @Html.Password("Password")
        <input class="btn btn-primary" type="submit" value="login" />
    }
  6. Create a Machine Key tag into web.config under System.Web tag in SingleSignOn, ApplciationA, and ApplicationB.
    <system.web>
        <machineKey validationKey="4B616C4E8BE5E18C3A1650939E88F3B0ED1AFC692919D7937DA68BBC552F04027DCF8BD31125E5E69094E1A4BA96731067BB57F0D3C34B63B9B03123703CD01A"
                    decryptionKey="EC095D7743D3368F22FB7F482D9F41AA911922EC753515BB"  
                    validation="HMACSHA384" decryption="DES" />
    </system.web>
    You can create your own machine keys through the below steps:
    • Open IIS manager.
    • Select the website name from the left panel.
    • In the right panel, double click on Machine Key icon under Asp.Net settings. Now click on Generate Keys button in the right panel to generate random machine keys.
  7. Add forms authentication tag to web.config of SingleSignOn, ApplciationA, and ApplicationB.
    <authentication mode="Forms">
       <forms name="SingleSignOnApp" loginUrl="http://localhost/SingleSignOn/Account/Login" timeout="525599" slidingExpiration="true">
       </forms>
    </authentication>
  8. We are using local IIS  localhost/SingleSignOn to configure it. To run it right-click on the project, choose Properties menu and choose Web.
  9. To test an SSO functionality, right-click on Home Controller in both ApplicationA and ApplicationB. Add Authorize attribute on the top of Home Controller that will redirect the unauthenticated users to SingleSignOn login.
    [Authorize]
    public class HomeController : Controller
     { 
        public ActionResult Index()
         {
            return View();
         }
     }
  10. Right-click on Action result, select Add View and add Index View for the HomeController in both ApplicationA and ApplicationB.
    @{
                    ViewBag.Title = "Application-A Home";
     }
    <h2>Application-A Home</h2>
    Welcome @User.Identity.Name
  11. Login using username and password. After a successful login, it will automatically redirect to http://localhost/ApplicationA.
  12. Now try the same process for ApplicationB and browse http://localhost/ApplicationB. You will see that it automatically logs in and redirect to ApplicationB.

Comments

Popular posts from this blog

Sitecore Installation Error: Failed to Start Service 'Sitecore Marketing Automation Engine'

Import CSV Data in Sitecore Using PowerShell: Part-3

Sitecore : The database principal owns a schema in the database, and cannot be dropped message