Single Sign-On (SSO) in ASP.NET Core Applications

Introduction

Single Sign-On (SSO) is a centralized user authentication service that allows a user to log in once and gain access to multiple applications. SSO enhances user convenience and security, reducing the need for multiple passwords and mitigating the risks of password fatigue. This article delves into implementing SSO in an ASP.NET Core application using IdentityServer4.

Understanding SSO

SSO delegates authentication responsibilities to a central identity provider (IdP). When a user attempts to access a service, the service redirects the user to the IDP for authentication. Upon successful authentication, the IDP issues a token the service uses to verify the user's identity.

Why Use SSO?

  1. Improved User Experience: Users log in once to access multiple applications.
  2. Enhanced Security: Centralized authentication reduces password-related risks.
  3. Simplified Management: Administrators manage a single authentication system.
  4. Compliance: Easier to enforce security policies and compliance requirements.

Implementing SSO with ASP.NET Core and IdentityServer4
 

Step 1. Setting Up IdentityServer4

  1. Create a new ASP.NET Core project.
    dotnet new mvc -n SSOApp
    cd SSOApp
    
  2. Add IdentityServer4 NuGet package.
    dotnet add package IdentityServer4
    dotnet add package IdentityServer4.AspNetIdentity
    
  3. Configure IdentityServer4 in Startup.cs.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();
        services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryIdentityResources(Config.IdentityResources)
            .AddInMemoryApiResources(Config.ApiResources)
            .AddInMemoryClients(Config.Clients)
            .AddAspNetIdentity<ApplicationUser>();
        services.AddAuthentication()
            .AddGoogle("Google", options =>
            {
                options.ClientId = "your-client-id";
                options.ClientSecret = "your-client-secret";
            });
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRouting();
        app.UseIdentityServer();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapDefaultControllerRoute();
        });
    }
    
  4. Define Identity Resources, API Resources, and Clients in Config. cs.
    public static class Config
    {
        public static IEnumerable<IdentityResource> IdentityResources =>
            new List<IdentityResource>
            {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile(),
            };
        public static IEnumerable<ApiResource> ApiResources =>
            new List<ApiResource>
            {
                new ApiResource("api1", "My API")
            };
        public static IEnumerable<Client> Clients =>
            new List<Client>
            {
                new Client
                {
                    ClientId = "client",
                    AllowedGrantTypes = GrantTypes.ClientCredentials,
                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },
                    AllowedScopes = { "api1" }
                }
            };
    }
    

Step 2. Setting Up a Client Application

  1. Create a new ASP.NET Core MVC project.
    dotnet new mvc -n ClientApp
    cd ClientApp
    
  2. Add necessary NuGet packages.
    dotnet add package Microsoft.AspNetCore.Authentication.OpenIdConnect
    dotnet add package Microsoft.AspNetCore.Authentication.Cookies
    
  3. Configure authentication in Startup. cs.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        })
        .AddCookie()
        .AddOpenIdConnect(options =>
        {
            options.Authority = "https://localhost:5001";
            options.ClientId = "client";
            options.ClientSecret = "secret";
            options.ResponseType = "code";
            options.SaveTokens = true;
            options.Scope.Add("api1");
            options.Scope.Add("offline_access");
        });
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapDefaultControllerRoute();
        });
    }
    

Step 3. Testing the SSO Implementation

  1. Run the IdentityServer4 and Client applications.
    dotnet run --project SSOApp
    dotnet run --project ClientApp
    
  2. Access the Client application: Navigate to the Client application URL (e.g., https://localhost:5002).
  3. Initiate Login: Click the login button to redirect you to the IdentityServer4 login page.
  4. Authenticate: Provide your credentials, and upon successful authentication, you will be redirected back to the Client application with the SSO session established.

Conclusion

Implementing Single Sign-On in ASP.NET Core applications using IdentityServer4 significantly improves user experience and security. By centralizing authentication, you streamline user management and enhance overall security. This article provides a comprehensive guide to setting up SSO in your ASP.NET Core applications, paving the way for a more efficient and secure authentication process.

References

Implementing SSO can seem daunting at first, but with the right tools and guidance, you can achieve a seamless and secure authentication system in your ASP.NET Core applications.