Single Sign-On (SSO) in .NET Core and Angular
๐ Single Sign-On (SSO) in .NET Core and Angular
Date: March 30, 2025
Single Sign-On (SSO) is an authentication mechanism that lets users log in once and access multiple applications without re-entering credentials. In this guide, we’ll implement SSO using IdentityServer4, OAuth 2.0, and OpenID Connect with .NET Core and Angular.
๐ ️ Step 1: Setting Up IdentityServer4 in .NET Core
1.1 Create Identity Server Project
dotnet new webapi -n IdentityServer
cd IdentityServer
dotnet add package IdentityServer4
1.2 Configure IdentityServer in Program.cs
using IdentityServer4.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using System.Collections.Generic;
var builder = WebApplication.CreateBuilder(args);
// IdentityServer setup
builder.Services.AddCors(); // ๐ Required for Angular
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(); // ⚠️ Not for production
var app = builder.Build();
app.UseCors(policy =>
policy.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
app.UseIdentityServer();
app.UseAuthorization();
app.MapGet("/", () => "✅ Identity Server Running");
app.Run();
⚠️ Note: DeveloperSigningCredential is only for development. Use a proper certificate in production.
๐ Step 2: Configuring Angular for SSO
2.1 Install OAuth2 OIDC Library
npm install angular-oauth2-oidc
2.2 Create auth-config.ts
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 Create auth.service.ts
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 Update app.component.ts
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: Run & Test
3.1 Start Identity Server
dotnet run
It should be available at http://localhost:5000
3.2 Start Angular App
ng serve
App runs at http://localhost:4200
3.3 Test Flow
- Click Login on Angular UI
- You are redirected to IdentityServer
- After login, redirected back to Angular
- Access protected resources using access token
✅ Pro Tip: For real-world apps, use HTTPS and set proper CORS & scopes per environment.
๐งพ Conclusion
You’ve now set up a fully working SSO solution using .NET Core IdentityServer4 and Angular. This improves security and user experience by allowing users to log in once across multiple apps.
- ✅ IdentityServer4 handles auth securely via OAuth2/OIDC
- ✅ Angular integrates using
angular-oauth2-oidc - ✅ SSO flow works with just one login across services
Comments
Post a Comment