Implementing Single Sign-On (SSO) in .NET Core and Angular

Implementing Single Sign-On (SSO) in .NET Core and Angular

Introduction

Single Sign-On (SSO) is a powerful authentication mechanism that enhances user experience and security by allowing users to log in once and access multiple applications without re-entering credentials. In this blog, we will walk through the implementation of SSO using OAuth 2.0 and OpenID Connect (OIDC) with IdentityServer4 in .NET Core and Angular.


Why Use SSO?

  • Improved User Experience: Users authenticate once and access multiple services without repeated logins.

  • Centralized Authentication: Easier user management and security enforcement.

  • Better Security: Reduces password fatigue and encourages strong authentication policies.

  • Scalability: Works well across multiple applications, making it ideal for enterprise solutions.


Step 1: Setting Up IdentityServer4 in .NET Core

IdentityServer4 is an open-source framework that enables authentication and authorization using OpenID Connect and OAuth2.

1.1 Create a New .NET Core Identity Server

Run the following command to create a new Web API project:

dotnet new webapi -n IdentityServer
cd IdentityServer
dotnet add package IdentityServer4

1.2 Configure IdentityServer in Program.cs

Modify Program.cs to add IdentityServer with clients, resources, and users.

using IdentityServer4.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using System.Collections.Generic;

var builder = WebApplication.CreateBuilder(args);

// Configure IdentityServer
builder.Services.AddIdentityServer()
    .AddInMemoryClients(new List<Client>
    {
        new Client
        {
            ClientId = "angular-client",
            AllowedGrantTypes = GrantTypes.Code,
            RequirePkce = true,
            RedirectUris = { "http://localhost:4200/callback" },
            PostLogoutRedirectUris = { "http://localhost:4200/logout" },
            AllowedScopes = { "openid", "profile", "api.read" },
            AllowAccessTokensViaBrowser = true
        }
    })
    .AddInMemoryIdentityResources(new List<IdentityResource>
    {
        new IdentityResources.OpenId(),
        new IdentityResources.Profile()
    })
    .AddInMemoryApiScopes(new List<ApiScope>
    {
        new ApiScope("api.read", "Read access to API")
    })
    .AddDeveloperSigningCredential();

var app = builder.Build();

app.UseIdentityServer();
app.UseAuthorization();

app.MapGet("/", () => "Identity Server Running");

app.Run();


Step 2: Configuring Angular with SSO

Angular will use the angular-oauth2-oidc library to handle authentication.

2.1 Install Dependencies

Run the following command in your Angular project:

npm install angular-oauth2-oidc

2.2 Configure OAuth Service (auth-config.ts)

Create a new file auth-config.ts in the Angular app.

import { AuthConfig } from 'angular-oauth2-oidc';

export const authConfig: AuthConfig = {
  issuer: 'http://localhost:5000',
  redirectUri: window.location.origin + '/callback',
  clientId: 'angular-client',
  scope: 'openid profile api.read',
  responseType: 'code',
  strictDiscoveryDocumentValidation: false
};

2.3 Setup Authentication Service (auth.service.ts)

Create auth.service.ts to manage authentication.

import { Injectable } from '@angular/core';
import { OAuthService } from 'angular-oauth2-oidc';
import { authConfig } from './auth-config';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  constructor(private oauthService: OAuthService) {
    this.configureSSO();
  }

  private configureSSO() {
    this.oauthService.configure(authConfig);
    this.oauthService.loadDiscoveryDocumentAndTryLogin();
  }

  login() {
    this.oauthService.initCodeFlow();
  }

  logout() {
    this.oauthService.logOut();
  }

  get isLoggedIn(): boolean {
    return this.oauthService.hasValidAccessToken();
  }
}

2.4 Integrate Login & Logout in Components

Modify app.component.ts to allow users to log in and out.

import { Component } from '@angular/core';
import { AuthService } from './auth.service';

@Component({
  selector: 'app-root',
  template: `
    <button *ngIf="!auth.isLoggedIn" (click)="auth.login()">Login</button>
    <button *ngIf="auth.isLoggedIn" (click)="auth.logout()">Logout</button>
  `
})
export class AppComponent {
  constructor(public auth: AuthService) { }
}


Step 3: Running the Application

3.1 Start Identity Server

dotnet run

It will run on http://localhost:5000.

3.2 Start Angular App

ng serve

It will run on http://localhost:4200.

3.3 Test SSO

  1. Click on the Login button in the Angular app.

  2. You will be redirected to IdentityServer for authentication.

  3. Once logged in, you will be redirected back to the Angular app.

  4. You can now access protected resources.


Conclusion

By implementing SSO using IdentityServer4 in .NET Core and Angular, we have successfully created a seamless and secure authentication experience. This approach simplifies user access across multiple applications while maintaining high security standards.

Comments

Popular posts from this blog

Multiline to singleline IN C# - CODING

EF Core interview questions for beginners

EF Core interview questions for experienced