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

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

Single Sign-On (SSO) is an authentication mechanism that allows users to log in once and gain access to multiple applications without needing to re-enter credentials. It enhances user experience and security by centralizing authentication. In this article, we will implement SSO using OAuth 2.0 and OpenID Connect (OIDC) with IdentityServer4 in .NET Core and Angular.

 

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

This setup provides a working SSO solution using IdentityServer4 in .NET Core and Angular. Users can authenticate once and securely access multiple applications without logging in again.

Comments

Popular posts from this blog

Promises in Angular

Mastering Your Angular Workflow: Essential CLI Commands for Efficient Development

Observables in Angular