A centralized user authentication system called Single Sign-On (SSO) enables users to log in just once and access numerous apps. By eliminating the need for several passwords and lowering the possibility of password fatigue, SSO improves user comfort and security. This article explores utilizing IdentityServer4 to provide SSO in an ASP.NET Core application.

Comprehending SSO
A central identity provider (IdP) is given authentication duties by SSO. The service sends the user to the IDP for authentication when they try to access it. The IDP provides a token that the service uses to confirm the user's identity after successful authentication.

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

Implementing SSO with ASP.NET Core and IdentityServer4
Step 1. Setting Up IdentityServer4

Create a new ASP.NET Core project
dotnet new mvc -n SSOApp
cd SSOApp


Add IdentityServer4 NuGet package
dotnet add package IdentityServer4
dotnet add package IdentityServer4.AspNetIdentity

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


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
Create a new ASP.NET Core MVC project
dotnet new mvc -n ClientApp
cd ClientApp

Add necessary NuGet packages
dotnet add package Microsoft.AspNetCore.Authentication.OpenIdConnect
dotnet add package Microsoft.AspNetCore.Authentication.Cookies

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
Run the IdentityServer4 and Client applications.
dotnet run --project SSOApp
dotnet run --project ClientApp


Access the Client application: Navigate to the Client application URL (e.g., https://localhost:5002).
Initiate Login: Click the login button to redirect you to the IdentityServer4 login page.
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.

HostForLIFE ASP.NET Core 9.0 Hosting

European Best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.