ASP.NET MVC

Single Sign On (SSO) In ASP.NET MVC

In this article, we are going to implement Single Sign-On (SSO) in ASP.NET MVC. for that I am going to demonstrate by creating new projects.

suppose you have multiple web applications and for authentication, you have to log in from each corresponding web application. but using Single Sign-On (SSO) you don’t need to log in multiple times. we can eliminate it using Single Sign-On (SSO). E.X- Users have to log in only once and they can able to access multiple web applications.

Enable Single Sign On

For enabling Single Sign On we have to use the key, which is machineKey and authentication (forms). All the Web Applications in which we have to enable SSO should have the same configuration.

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

Implement Single Sign On in ASP.NET MVC

below are the steps for implementing SSO in ASP.NET MVC.

1. Create a blank MVC solution.

2. Add three empty ASP.NET MVC Web Applications to the solution.

– The First one is named SSOBase

– The second one is named WebApplication1

– The Third one is named WebApplication2

3. Now Add an AccountController in SSOBase Project, which contains the code for login.

4. Here, in AccountController we can write some code for LOG IN/AUTHENTICATION. For the demo, I have usedFormsAuthentication.Authenticate a method that is going to check the credentials stored in web.config and authenticates if the username and the password are valid or not. you can check it using SQL Server or any other database of your choice. below is demo code in the AccountController.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace SSOBase.Controllers
{
    public class AccountController : Controller
    {
        // GET: Account
        public ActionResult Index()
        {
            return View();
        }

        [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();
            }
        }

    }
}

5. For the users to log in, we need to add an HTML form to our login view page. below is the code for Login.cshtml

@{
    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" />
}

6. Now we have to add machineKey in the web.config of SSOBase, WebApplication1, WebApplication2. machineKey have to be added insystem.web, you can generate machine keys online from any website. following are my machine key which I have added in web.config.

<machineKey validationKey="4305AAA03B45563C2006C18C7BDEA14B7001CAF6C25486B9FD7CC9284E00ED28DC36F2DBE621636DF420AA471974640F92C5C1892EA6AC1AA9FF5984A86CD0BE" decryptionKey="48CC02FA2CFF15EFE21CE8633999B993A73E2C23A8AC06830E8ABAE55DF0D60C" validation="SHA1" decryption="AES" />

7. Now we have to add forms authentication in the web.config of SSOBase, WebApplication1, WebApplication2. we have to add it in system.web. <credentials>…</credentials> is not required for WebApplication1 and WebApplication2. as we are going to authenticate users only from AccountController of SSOBase.

<authentication mode="Forms">
  <forms name="SingleSignOn"
  loginUrl="http://localhost/SSOBase/Account/Login"
  timeout="480" slidingExpiration="true">
    <credentials passwordFormat="SHA1">
      <user name="demo"
      password="89e495e7941cf9e40e6980d14a16bf023ccd4c91"/>
      <!--password = demo-->
    </credentials>
  </forms>
</authentication>

8. Here we are using local IIS for server settings. and we configure it to run from localhost/SSOBase. we can do it by right-click on the project, then selecting the properties, and selecting the web tab. below are reference images for it.

9. Now for Single Sign-On, add HomeController in both WebApplication1, WebApplication2. also add Authorize attribute on the HomeController , it will send users to SSOBase Login when unauthenticated.

using System.Web.Mvc;

namespace WebApplication1.Controllers
{
    [Authorize]
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
    }
}

10. Now we just need to add an Index view in the HomeController for both WebApplication1 and  WebApplication2.

WebApplication1/Home/Index.cshtml

@{
    ViewBag.Title = "Index";
}


<h2>Web Application 1 - Home</h2>

Logged in as @User.Identity.Name

WebApplication2/Home/Index.cshtml

@{
    ViewBag.Title = "Index";
}


<h2>Web Application 2 - Home</h2>

Logged in as @User.Identity.Name

11. Now browse for http://localhost/WebApplication1. and if you are not authenticated then It will automatically redirect to http://localhost/SSOBase/Account/Login?ReturnUrl=%2fWebApplication1%2f.

12. Now log in using username and password both as the demo. On successfully logging in, it will automatically redirect you to http://localhost/WebApplication1.

13. Now browse to http://localhost/WebApplication2/. it will automatically log in and it shows the WebApplication2 index page.

Hope you like it and will be useful. Thank You 🙂

Also check, Generate C# Model Class From Table In MSSQL

Tabish Rangrej

Tabish Rangrej is an Experienced .NET Team Leader, software engineer, and Author with a demonstrated history of working in the IT industry. He has quite well experience in developing, communicating, managing, and writing in his field. He has strong skills and knowledge of ASP.NET C#, ASP.NET MVC, ASP.NET CORE, Angular, AngularJS, Web API, SQL, Entity Framework, JavaScript, Jquery, Different Integrations like Quickbooks, Stripe, Google APIs, Zoho, Orion, Xero, etc., Different versioning tools like TFS, SVN, GIT, etc. and Windows services. Strong engineering professional with a Master of Computer Applications - MCA focused on Computer Science from Veer Narmad South Gujarat University, Surat. Tabish is always ready to accept new challenges and learn new things, he would like to serve better for the community.

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

2 years ago