Click here to Skip to main content
15,885,366 members
Articles / Web Development / ASP.NET

Implementation of Single Sign On (SSO) in ASP.NET MVC

Rate me:
Please Sign up or sign in to vote.
4.62/5 (18 votes)
16 Oct 2016Ms-PL2 min read 136.3K   27   11
Implementation of single sign on in ASP.NET MVC

What is Single Sign On (SSO)?

To access any secured page in a web application, the user needs to authenticate and if the user want to access multiple web applications, then the user has to login for each of those applications individually. Logging in multiple times can be eliminated with Single Sign On, i.e., user has to login only once and can access web multiple applications.

image

How to Enable Single Sign On?

The key for enabling Single Sign On is machineKey and authentication (forms). All the Web Applications should have the same configuration to make it work.

XML
<machineKey validationKey="<MachineKey>"
            decryptionKey="<DecryptionKey>"
            validation="<CryptoAlgorithm>"
            decryption="<CryptoAlgorithm>" />
<authentication mode="Forms">
  <forms name="SingleSignOn"
  loginUrl="<SSOLoginURL>" timeout="480"
  slidingExpiration="true">
   </forms>
</authentication>

How to Implement Single Sign On in ASP.NET MVC?

Implementing SSO in ASP.NET MVC is very simple. Below is the step by step approach to implement it.

  1. Open Visual Studio, create a blank solution (I always like to start off with a blank solution).

    image

  2. Now add three empty ASP.NET MVC Web Applications (SSO, WebApp1 & WebApp2) to the solution.

    image

    image

  3. The solution should look something like below:

    image

  4. Add an AccountController in SSO, this should contain the code for login.

    image

    image

  5. Write some simple forms authentication code like the below in the AccountController. For demo purposes, I am using FormsAuthentication.Authenticate method which will simply check the credentials stored in web.config and authenticates if username and the password are valid, you can also validate username and password stored in SQL Server database.
    JavaScript
    using System.Web.Mvc;
    using System.Web.Security;
     
    namespace SSO.Controllers
    {
      public class AccountController : Controller
      {
        [AllowAnonymous]
        public 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 details");
            ViewBag.ReturnUrl = returnUrl;
            return View();
          }
        }
      }
    }
  6. Now we need to add an html form in the login view for the users to login.
    HTML
    @{
      ViewBag.Title = "Login";
    }
     
    <h2>Login</h2>
    @using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl }))
    {
      @Html.ValidationSummary()
      @Html.AntiForgeryToken()
      <div class="form-group">
        @Html.Label("Username")
        @Html.Editor("UserName")
      </div>
      <div class="form-group">
        @Html.LabelForModel("Password")
        @Html.Password("Password")
      </div>
      <input class="btn btn-primary" 
      type="submit" value="Login" />
    }
  7. Add machineKey to web.config of SSO, WebApp1 and WebApp2. You can create your own machine keys by following this or simply generate online from here. The machineKey should be added under system.web.
    XML
    <system.web>
      <machineKey validationKey="E4451576F51E0562D91A1748DF7AB3027FEF3C2CCAC46D
      756C833E1AF20C7BAEFFACF97C7081ADA4648918E0B56BF27D1699A6EB2D9B6967A562CAD14767F163"
                  decryptionKey="6159C46C9E288028ED26F5A65CED7317A83CB3485DE8C592"
                  validation="HMACSHA256" decryption="AES" />
    
  8. Add forms authentication to web.config of SSO, WebApp1 and WebApp2. For WebApp1 and WebApp2 <credentials>…</credentials> is not required as we will authenticate users from only AccountController of SSO.
    XML
    <authentication mode="Forms">
      <forms name="SingleSignOn"
      loginUrl="http://localhost/SSO/Account/Login"
      timeout="480" slidingExpiration="true">
        <credentials passwordFormat="SHA1">
          <user name="demo"
          password="89e495e7941cf9e40e6980d14a16bf023ccd4c91"/>
          <!--password = demo-->
        </credentials>
      </forms>
    </authentication>
    
  9. As you can see in the above, I am using local IIS localhost/SSO to configure it to run from there, simply right click on project, select the properties and select web like below:

    image

  10. To test Single Sign On, add HomeController in both WebApp1 and WebApp2. Do not forget to add Authorize attribute on the HomeController, that will send the unauthenticated users to SSO Login.
    JavaScript
    [Authorize]
    public class HomeController : Controller
    {
      //
      // GET: /Home/
     
      public ActionResult Index()
      {
        return View();
      }
    }
  11. Add Index view for the HomeController in both WebApp1 and WebApp2 respectively.

    WebApp1/Home/Index.cshtml

    HTML
    @{
        ViewBag.Title = "Web App1 Home";
    }
     
    <h2>Web App1 Home</h2>
     
    Logged in as @User.Identity.Name

    WebApp2/Home/Index.cshtml

    HTML
    @{
      ViewBag.Title = "Web App2 Home";
    }
     
    <h2>Web App2 Home</h2>
     
    Logged in as @User.Identity.Name
  12. Now browse for http://localhost/WebApp1. It will automatically redirect to http://localhost/SSO/Account/Login?ReturnUrl=%2fWebApp1%2f.

    image

  13. Login using Username and Password as demo. On logging in successfully, it will automatically take you to http://localhost/WebApp1.

    image

  14. Now try to browse http://localhost/WebApp2/. You will see that it will automatically login and it shows message as Logged in as demo.

    image

You can get the source code for demo from GitHub at https://github.com/arunendapally/SSO.

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)


Written By
Architect Thomson Reuters
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
PraiseMy vote of 0 Pin
vhlpro19-Jul-20 0:05
vhlpro19-Jul-20 0:05 
QuestionHow Can I provider return URL to other project such as WebApp1 or WebApp2 Pin
rIdDhS24-Dec-19 17:10
rIdDhS24-Dec-19 17:10 
Questionlogin timeout Pin
heru hendrawan7-Aug-19 22:14
heru hendrawan7-Aug-19 22:14 
how to set the duration of the login, if logout occurs every 20 minutes?
GeneralMy vote of 4 Pin
Ali Javani17-Dec-18 19:36
Ali Javani17-Dec-18 19:36 
QuestionShowing Invalid username/password Pin
Sam_IN26-Jul-18 21:32
Sam_IN26-Jul-18 21:32 
AnswerRe: Showing Invalid username/password Pin
Member 136630932-Sep-18 23:19
Member 136630932-Sep-18 23:19 
QuestionCan i use this for integrating with Ping One ? Pin
Member 127558998-Jan-18 2:03
Member 127558998-Jan-18 2:03 
QuestionThis works well in the architecture that the related sites belong to the same domain Pin
dinhhungitsoft20-Oct-16 23:08
dinhhungitsoft20-Oct-16 23:08 
AnswerRe: This works well in the architecture that the related sites belong to the same domain Pin
sairfan13-May-17 7:23
sairfan13-May-17 7:23 
GeneralRe: This works well in the architecture that the related sites belong to the same domain Pin
Arun Endapally30-May-17 8:22
professionalArun Endapally30-May-17 8:22 
PraiseNice article... Pin
Siva Saripilli18-Oct-16 11:21
professionalSiva Saripilli18-Oct-16 11:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.