In questo capitolo affrontiamo un aspetto cruciale delle moderne applicazioni web: la sicurezza delle API. Proteggere le API garantisce che solo gli utenti autorizzati possano accedere ai dati e modificarli.
Per ottenerlo usiamo Keycloak, una soluzione open source di Identity and Access Management (IAM). Keycloak offre solide funzionalità di autenticazione e autorizzazione, semplificando l’implementazione di meccanismi di sicurezza standard come OAuth 2.0 e OpenID Connect.
L’integrazione di Keycloak avverrà su due fronti:
- Frontend (Angular): configuriamo l’applicazione Angular per interagire con Keycloak, permettendo agli utenti di autenticarsi e di ottenere i token di accesso per le chiamate sicure alle API di backend. La libreria
keycloak-angularfacilita questa integrazione. - Backend (Django): proteggiamo le API Django in modo che per ogni richiesta sia necessario un token di accesso valido emesso da Keycloak. Django validerà questi token ed estrarrà le informazioni su utente e ruoli, abilitando un controllo degli accessi granulare basato sui ruoli di Keycloak.
I passaggi seguenti descrivono come configurare Keycloak, integrare il client Angular e mettere in sicurezza le view di Django.
Installazione di Keycloak
Per prima cosa crea un nuovo schema in MySQL (vedi la parte 3). Apri il terminale e accedi a MySQL:
# mysql -h 127.0.0.1 -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1289
Server version: 8.3.0 MySQL Community Server - GPL
Copyright (c) 2000, 2024, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
Aggiungi un nuovo utente keycloak e imposta una password:
mysql> CREATE USER keycloak@'%' IDENTIFIED BY 'keycloak';
Query OK, 0 rows affected (0,14 sec)
Crea un nuovo schema keycloak:
mysql> CREATE DATABASE keycloak;
Query OK, 1 row affected (0,01 sec)
Concedi i privilegi sul nuovo schema all’utente keycloak:
mysql> GRANT ALL PRIVILEGES ON keycloak.* TO keycloak@'%';
Query OK, 0 rows affected (0,02 sec)
Ricarica i privilegi:
mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0,01 sec)
Ora installa Keycloak. Per configurare rapidamente un ambiente di sviluppo con Docker, aggiorna il tuo file docker-compose.yml:
name: library
services:
db:
image: mysql
container_name: mysql
restart: always
env_file:
- path: ./environments/mysql.env
required: true
ports:
- "3306:3306"
volumes:
- db_data:/var/lib/mysql
networks:
- backend
keycloak:
image: quay.io/keycloak/keycloak:latest
container_name: keycloak
command: start-dev
networks:
- backend
depends_on:
- db
env_file:
- path: ./environments/keycloak.env
required: true
ports:
- "8080:8080"
restart: unless-stopped
volumes:
db_data: {}
networks:
backend:
driver: bridge
Definisci il file di ambiente environments/keycloak.env:
KEYCLOAK_ADMIN=admin
KEYCLOAK_ADMIN_PASSWORD=keycloak
KC_DB=mysql
KC_DB_URL_HOST=mysql
KC_DB_URL_DATABASE=keycloak
KC_DB_USERNAME=keycloak
KC_DB_PASSWORD=keycloak
Esegui il deploy di Keycloak:
# docker-compose up -d
[+] Running 5/5
✔ keycloak Pulled 10.6s
✔ 830112cfee05 Pull complete 1.8s
✔ f79851aee01e Pull complete 6.1s
✔ d36e3fd02231 Pull complete 7.0s
✔ cc67d5854a75 Pull complete 7.1s
[+] Running 3/3
✔ Network library_default Created 0.1s
✔ Container mysql Running 0.0s
✔ Container keycloak Started 0.9s
Puoi accedere alla console di amministrazione di Keycloak all’indirizzo http://127.0.0.1:8080.

Configurare Keycloak
Un realm in Keycloak è uno spazio isolato per gestire utenti, ruoli, gruppi e client. Ogni realm è indipendente, e ti permette di gestire più applicazioni o ambienti all’interno della stessa istanza di Keycloak.
Creare un nuovo realm: library-realm
Per organizzare utenti, ruoli e client della tua applicazione:
- Accedi alla console di amministrazione di Keycloak
Apri http://127.0.0.1:8080 e accedi con le credenziali di amministratore definite nel file di ambiente. - Crea il realm
- Clicca su
Manage realmsnella barra laterale. - Clicca su
Create realm. - Inserisci
library-realmcome Realm Name. - Se vuoi, aggiungi una descrizione.
- Clicca su Create.
- Clicca su

Il tuo nuovo realm library-realm è pronto. Ora puoi configurare client, ruoli e utenti al suo interno.
Creare un nuovo client: library-web
Un client in Keycloak rappresenta un’applicazione o un servizio che interagisce con il server Keycloak per autenticare gli utenti e ottenere token di sicurezza. I client possono essere applicazioni frontend (come app Angular o React), servizi di backend o qualsiasi sistema che debba usare Keycloak per autenticazione e autorizzazione. Definire un client permette a Keycloak di gestire come gli utenti effettuano il login nella tua applicazione, quali permessi hanno e come vengono emessi i token.
Passaggi per creare un nuovo client: library-web
Per permettere alla tua applicazione frontend di autenticare gli utenti tramite Keycloak, devi creare un nuovo client pubblico:
- Vai ai Clients
- Assicurati di trovarti nel
library-realm. - Clicca su Clients nella barra laterale.
- Assicurati di trovarti nel
- Crea il client
- Clicca su
Create client. - In
General Settings:Client type:OpenID ConnectClient ID:library-webClient Name:Library Web- Clicca su Next.
- Clicca su

- In
Capability config:- Imposta
Client Authenticationsuoff. - In
Authentication Flowseleziona soloStandard Flow. - Clicca su Next.
- Imposta

- In
Login settings:- Imposta
Valid redirect URIssu*. - Imposta
Web originssu*. - Clicca su Save.
- Imposta

Il client library-web è ora configurato. Questo client permette al tuo frontend Angular di reindirizzare gli utenti a Keycloak per l’autenticazione e di ricevere i token per le chiamate sicure alle API.
Configurare Keycloak-Angular
Per integrare il frontend Angular 19 con Keycloak usando keycloak-angular e il client library-web:
1. Installare le dipendenze
# npm install keycloak-angular keycloak-js
added 100 packages, and audited 1119 packages in 2s
183 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
2. Aggiungere le impostazioni di Keycloak in environments.development.ts
Modifica environments.development.ts e aggiungi la configurazione di Keycloak:
export const environment = {
production: false,
api_url: "http://127.0.0.1:8000",
keycloak: {
url: "http://127.0.0.1:8080",
realm: "library-realm",
client_id: "library-web",
},
};
3. Configurare Keycloak in app.config.ts
Aggiorna il file app.config.ts per inizializzare Keycloak all’avvio dell’app:
Aggiungi il nuovo provideKeycloakAngular
// app.config.ts
export const provideKeycloakAngular = () =>
provideKeycloak({
config: {
url: environment.keycloak.url,
realm: environment.keycloak.realm,
clientId: environment.keycloak.client_id,
},
initOptions: {
onLoad: "check-sso",
silentCheckSsoRedirectUri: window.location.origin + "/silent-check-sso.html",
},
features: [
withAutoRefreshToken({
onInactivityTimeout: "logout",
sessionTimeout: 60 * 60 * 1000, // 1 hour
}),
],
providers: [AutoRefreshTokenService, UserActivityService],
});
Questo codice definisce una funzione chiamata provideKeycloakAngular che configura l’autenticazione in un’applicazione Angular usando Keycloak, una soluzione di identity and access management.
- provideKeycloak: questa funzione inizializza Keycloak con la configurazione fornita.
- config: contiene i dettagli di connessione a Keycloak, come l’URL del server, il realm e il client ID. Questi valori vengono presi dalle impostazioni di ambiente dell’applicazione.
- initOptions: imposta le opzioni di inizializzazione di Keycloak.
onLoad: "check-sso"indica a Keycloak di verificare se l’utente ha già effettuato l’accesso (Single Sign-On).silentCheckSsoRedirectUrispecifica un URL usato per i controlli SSO silenziosi, che permettono all’app di verificare lo stato del login senza reindirizzare l’utente.
- features:
withAutoRefreshTokenabilita l’aggiornamento automatico del token di autenticazione.onInactivityTimeout: "logout"disconnette l’utente dopo un periodo di inattività.sessionTimeout: 60 * 60 * 1000imposta il timeout di sessione a 1 ora.
- providers: registra i servizi (
AutoRefreshTokenService,UserActivityService) che aiutano a gestire l’aggiornamento del token e l’attività dell’utente.
Importa il nuovo provider
export const appConfig: ApplicationConfig = {
providers: [
provideKeycloakAngular(),
// ... existing code ...
],
};
Aggiungi silent-check-sso.html nella directory public:
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Silent SSO Check</title>
</head>
<body>
<script>
parent.postMessage(location.href, location.origin);
</script>
</body>
</html>
4. Creare un Auth Guard
Genera una guard di Angular:
# ng generate guard Auth
? Which type of guard would you like to create? (Select CanActivate)
❯◉ CanActivate
◯ CanActivateChild
◯ CanDeactivate
◯ CanMatch
✔ Which type of guard would you like to create? CanActivate
CREATE src/app/auth.guard.spec.ts (461 bytes)
CREATE src/app/auth.guard.ts (128 bytes)
// auth.guard.ts
import { ActivatedRouteSnapshot, CanActivateFn, RouterStateSnapshot, UrlTree } from "@angular/router";
import { AuthGuardData, createAuthGuard } from "keycloak-angular";
const isAccessAllowed = async (route: ActivatedRouteSnapshot, _: RouterStateSnapshot, authData: AuthGuardData): Promise<boolean | UrlTree> => {
const { authenticated, grantedRoles } = authData;
if (authenticated) {
return true;
}
return false;
};
export const authGuard: CanActivateFn = createAuthGuard<CanActivateFn>(isAccessAllowed);
Questo codice definisce una guard di autenticazione personalizzata per un’applicazione Angular che usa la libreria keycloak-angular. Lo scopo di una guard di autenticazione è controllare l’accesso a determinate route in base allo stato di autenticazione dell’utente.
Parti principali:
- Import:
ActivatedRouteSnapshot,CanActivateFn,RouterStateSnapshoteUrlTreevengono importati dal modulo router di Angular.AuthGuardDataecreateAuthGuardvengono importati dakeycloak-angular, che aiuta a integrare l’autenticazione Keycloak.
- Funzione isAccessAllowed:
- Questa funzione asincrona riceve la route corrente, lo stato del router e i dati di autenticazione.
- Estrae
authenticatedegrantedRolesdaauthDatatramite destrutturazione. - Se l’utente è autenticato (
authenticatedè true) restituiscetrue, consentendo l’accesso alla route. - Altrimenti restituisce
false, negando l’accesso.
- Export di authGuard:
authGuardviene creata passando la funzioneisAccessAllowedacreateAuthGuard.- Questa guard può essere usata nelle definizioni delle route di Angular per proteggerle e garantire che solo gli utenti autenticati possano accedervi.
Al momento la guard controlla solo se l’utente è autenticato. Più avanti limiteremo l’accesso in base ai ruoli dell’utente, aggiungendo logica a grantedRoles.
5. Proteggere le route nel router
Applica la guard alle route protette:
// app.routes.ts
import { Routes } from "@angular/router";
import { AuthGuard } from "./auth.guard";
export const routes: Routes = [
{
path: "protected",
loadComponent: () => import("./protected/protected.component").then((m) => m.ProtectedComponent),
canActivate: [AuthGuard],
},
// ...other routes
];
Usare Keycloak nei componenti
Aggiorna la tua app per gestire l’autenticazione e valutare i ruoli degli utenti.
Aggiorna library.component.html:
<h2>Books</h2>
<app-books-list></app-books-list>
<hr />
<div class="library-footer">
<a mat-raised-button color="primary" (click)="openAddBookDialog()"> <mat-icon>add</mat-icon> Add New Book </a>
</div>
<app-library-notification></app-library-notification>
Aggiorna gli import in library.component.ts:
// ... existing code ...
import { LibraryNotificationComponent } from '../library-notification/library-notification.component';
@Component({
selector: 'app-library',
imports: [
MatButtonModule,
MatIconModule,
BooksListComponent,
LibraryNotificationComponent,
],
// ... existing code ...
})
Aggiorna app.component.html:
<h1>{{ title }}</h1>
<div class="library">
<router-outlet></router-outlet>
</div>
Rimuoviamo <app-library> e <app-library-notification>. Aggiorna app.component.ts:
import { Component, effect, OnInit } from "@angular/core";
import { RouterOutlet } from "@angular/router";
import Keycloak from "keycloak-js";
import { KEYCLOAK_EVENT_SIGNAL, KeycloakEventType, typeEventArgs, ReadyArgs } from "keycloak-angular";
import { inject } from "@angular/core";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrl: "./app.component.scss",
imports: [RouterOutlet],
})
/**
* The `AppComponent` serves as the root component of the Library application.
* It initializes the application state and interacts with the `LibraryService`
* to fetch and display a list of books.
*
* @implements {OnInit}
*/
export class AppComponent implements OnInit {
title = "Library";
authenticated = false;
keycloakStatus: string | undefined;
private readonly keycloak = inject(Keycloak);
private readonly keycloakSignal = inject(KEYCLOAK_EVENT_SIGNAL);
constructor() {
effect(() => {
const keycloakEvent = this.keycloakSignal();
console.log("Keycloak event:", keycloakEvent);
this.keycloakStatus = keycloakEvent.type;
if (this.keycloakStatus === KeycloakEventType.Ready) {
this.authenticated = typeEventArgs<ReadyArgs>(keycloakEvent.args);
console.log("Keycloak is ready:", this.authenticated);
} else if (this.keycloakStatus === KeycloakEventType.AuthLogout) {
this.authenticated = false;
} else {
console.log("Keycloak status:", this.keycloakStatus);
}
});
}
ngOnInit(): void {
if (!this.keycloak.authenticated) {
this.keycloak.login().then(() => {
if (this.keycloak.authenticated && this.keycloak.token) {
console.log("Keycloak token:", this.keycloak.token);
this.authenticated = true;
}
});
} else {
if (this.keycloak.token) {
console.log("Keycloak token:", this.keycloak.token);
}
}
}
}
Questo codice gestisce l’autenticazione tramite Keycloak.
Punti chiave:
- Proprietà:
title: imposta il titolo del componente su “Library”.authenticated: tiene traccia del fatto che l’utente abbia effettuato l’accesso.keycloakStatus: memorizza il tipo di evento Keycloak corrente.keycloakekeycloakSignal: servizi iniettati per interagire con Keycloak e ascoltarne gli eventi.
- Costruttore:
- Imposta un
effectreattivo che ascolta gli eventi di Keycloak. - Aggiorna
keycloakStatuseauthenticatedin base al tipo di evento:- Se Keycloak è “Ready”, verifica se l’utente è autenticato.
- Se l’utente si disconnette, imposta
authenticatedsufalse. - Registra in console gli altri stati degli eventi a scopo di debug.
- Imposta un
- ngOnInit():
- All’inizializzazione del componente verifica se l’utente è autenticato.
- In caso contrario avvia il processo di login di Keycloak.
- Dopo il login, se sono presenti autenticazione e token, imposta
authenticatedsutruee registra il token in console.
Questo aggiornamento garantisce che l’utente sia autenticato con Keycloak all’avvio dell’app e reagisca agli eventi di autenticazione. Sfrutta la dependency injection e le funzionalità di programmazione reattiva di Angular per gestire lo stato di autenticazione.
Infine aggiorniamo i nostri moduli di routing:
library-routing.module.ts
import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { BookComponent } from "./components/book/book.component";
import { LibraryComponent } from "./components/library/library.component";
const routes: Routes = [
{ path: "", component: LibraryComponent },
{ path: "books/:id", component: BookComponent },
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class LibraryRoutingModule {}
{ path: "", component: LibraryComponent }
Significa che quando l’utente naviga all’URL radice (nessun percorso) viene mostrato ilLibraryComponent.
app.routes.ts
import { Routes } from "@angular/router";
import { authGuard } from "./auth.guard";
export const routes: Routes = [
{
path: "library",
loadChildren: () => import("./modules/library/library.module").then((m) => m.LibraryModule),
canActivate: [authGuard],
},
{ path: "", redirectTo: "/library", pathMatch: "full" },
{ path: "**", redirectTo: "/library", pathMatch: "full" },
];
routes: Routes = [...]: dichiara un array di oggetti route, che Angular usa per stabilire quale componente o modulo caricare in base al percorso dell’URL.- Primo oggetto route:
path: "library": quando il percorso dell’URL è library, questa route viene attivata.loadChildren: usa il lazy loading per caricare ilLibraryModulesolo quando si accede alla route library. Questo migliora le prestazioni evitando di caricare il modulo finché non serve.canActivate: [authGuard]: protegge la route con una guard di autenticazione. Solo gli utenti che superano il controllo diauthGuardpossono accedervi.
- Secondo oggetto route:
path: "": quando il percorso dell’URL è vuoto (percorso radice), l’utente viene reindirizzato a library.redirectTo: "/library": specifica la destinazione del reindirizzamento.pathMatch: "full": garantisce che il reindirizzamento avvenga solo quando l’intero percorso è vuoto.
- Terzo oggetto route:
path: "**": è una route wildcard che corrisponde a qualsiasi percorso non intercettato in precedenza.redirectTo: "/library": reindirizza tutti i percorsi sconosciuti a library.pathMatch: "full": garantisce che il reindirizzamento si applichi all’intero percorso non corrispondente.
Ora, quando proviamo a navigare nella nostra app su http://127.0.0.1:4200, veniamo reindirizzati alla pagina di login di keycloak. Dobbiamo quindi andare nella console di amministrazione di Keycloak e inserire un nuovo utente nel library-realm.
Vai su “Users” e clicca su Create new user.

Inserisci uno username, abilita Email verified e clicca su Create.

Vai alla scheda Credentials, clicca su Set password, imposta e conferma la password, disattiva il flag Temporary e clicca su Save.

Ora puoi accedere all’app. Dopo il login Keycloak potrebbe richiedere email, nome e cognome. Invia i dati richiesti.
Sarai autenticato e reindirizzato alla route /library.

Autenticazione del webservice
Ora integriamo una classe Authenticator in Django per proteggere le tue API.
Per prima cosa proteggi i tuoi servizi usando DEFAULT_PERMISSION_CLASSES in settings.py:
# ... exsting code ...
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
# ...
}
# ... exsting code ...
In alternativa, imposta permission_classes nelle tue classi ViewSet:
# ... exsting code ...
from rest_framework import permissions
class AuthorViewSet(viewsets.ModelViewSet):
# ... exsting code ...
permission_classes = [permissions.IsAuthenticated]
La proprietà permission_classes sovrascrive l’impostazione DEFAULT_PERMISSION_CLASSES.
Ora, aprendo l’app, otterrai un errore che indica che non hai i permessi per accedere ai dati.

Installare la libreria python-keycloak
Installa la libreria:
# pip install python-keycloak
Collecting python-keycloak
Using cached python_keycloak-5.5.0-py3-none-any.whl.metadata (6.0 kB)
Collecting aiofiles>=24.1.0 (from python-keycloak)
Using cached aiofiles-24.1.0-py3-none-any.whl.metadata (10 kB)
Collecting async-property>=0.2.2 (from python-keycloak)
Using cached async_property-0.2.2-py2.py3-none-any.whl.metadata (5.3 kB)
Collecting deprecation>=2.1.0 (from python-keycloak)
Using cached deprecation-2.1.0-py2.py3-none-any.whl.metadata (4.6 kB)
Collecting httpx>=0.23.2 (from python-keycloak)
Using cached httpx-0.28.1-py3-none-any.whl.metadata (7.1 kB)
Collecting jwcrypto>=1.5.4 (from python-keycloak)
Using cached jwcrypto-1.5.6-py3-none-any.whl.metadata (3.1 kB)
Collecting requests>=2.20.0 (from python-keycloak)
Using cached requests-2.32.3-py3-none-any.whl.metadata (4.6 kB)
Collecting requests-toolbelt>=0.6.0 (from python-keycloak)
Using cached requests_toolbelt-1.0.0-py2.py3-none-any.whl.metadata (14 kB)
Collecting packaging (from deprecation>=2.1.0->python-keycloak)
Using cached packaging-25.0-py3-none-any.whl.metadata (3.3 kB)
Collecting anyio (from httpx>=0.23.2->python-keycloak)
Using cached anyio-4.9.0-py3-none-any.whl.metadata (4.7 kB)
Collecting certifi (from httpx>=0.23.2->python-keycloak)
Using cached certifi-2025.4.26-py3-none-any.whl.metadata (2.5 kB)
Collecting httpcore==1.* (from httpx>=0.23.2->python-keycloak)
Using cached httpcore-1.0.9-py3-none-any.whl.metadata (21 kB)
Collecting idna (from httpx>=0.23.2->python-keycloak)
Using cached idna-3.10-py3-none-any.whl.metadata (10 kB)
Collecting h11>=0.16 (from httpcore==1.*->httpx>=0.23.2->python-keycloak)
Using cached h11-0.16.0-py3-none-any.whl.metadata (8.3 kB)
Collecting cryptography>=3.4 (from jwcrypto>=1.5.4->python-keycloak)
Using cached cryptography-44.0.3-cp39-abi3-macosx_10_9_universal2.whl.metadata (5.7 kB)
Requirement already satisfied: typing-extensions>=4.5.0 in /Users/rgiannetto/Developer/library/venv/lib/python3.12/site-packages (from jwcrypto>=1.5.4->python-keycloak) (4.13.2)
Collecting cffi>=1.12 (from cryptography>=3.4->jwcrypto>=1.5.4->python-keycloak)
Using cached cffi-1.17.1-cp312-cp312-macosx_11_0_arm64.whl.metadata (1.5 kB)
Collecting pycparser (from cffi>=1.12->cryptography>=3.4->jwcrypto>=1.5.4->python-keycloak)
Using cached pycparser-2.22-py3-none-any.whl.metadata (943 bytes)
Collecting charset-normalizer<4,>=2 (from requests>=2.20.0->python-keycloak)
Downloading charset_normalizer-3.4.2-cp312-cp312-macosx_10_13_universal2.whl.metadata (35 kB)
Collecting urllib3<3,>=1.21.1 (from requests>=2.20.0->python-keycloak)
Using cached urllib3-2.4.0-py3-none-any.whl.metadata (6.5 kB)
Collecting sniffio>=1.1 (from anyio->httpx>=0.23.2->python-keycloak)
Using cached sniffio-1.3.1-py3-none-any.whl.metadata (3.9 kB)
Using cached python_keycloak-5.5.0-py3-none-any.whl (77 kB)
Using cached aiofiles-24.1.0-py3-none-any.whl (15 kB)
Using cached async_property-0.2.2-py2.py3-none-any.whl (9.5 kB)
Using cached deprecation-2.1.0-py2.py3-none-any.whl (11 kB)
Using cached httpx-0.28.1-py3-none-any.whl (73 kB)
Using cached httpcore-1.0.9-py3-none-any.whl (78 kB)
Using cached h11-0.16.0-py3-none-any.whl (37 kB)
Using cached jwcrypto-1.5.6-py3-none-any.whl (92 kB)
Using cached cryptography-44.0.3-cp39-abi3-macosx_10_9_universal2.whl (6.7 MB)
Using cached cffi-1.17.1-cp312-cp312-macosx_11_0_arm64.whl (178 kB)
Using cached requests-2.32.3-py3-none-any.whl (64 kB)
Downloading charset_normalizer-3.4.2-cp312-cp312-macosx_10_13_universal2.whl (199 kB)
Using cached idna-3.10-py3-none-any.whl (70 kB)
Using cached urllib3-2.4.0-py3-none-any.whl (128 kB)
Using cached certifi-2025.4.26-py3-none-any.whl (159 kB)
Using cached requests_toolbelt-1.0.0-py2.py3-none-any.whl (54 kB)
Using cached anyio-4.9.0-py3-none-any.whl (100 kB)
Using cached sniffio-1.3.1-py3-none-any.whl (10 kB)
Using cached packaging-25.0-py3-none-any.whl (66 kB)
Using cached pycparser-2.22-py3-none-any.whl (117 kB)
Installing collected packages: async-property, urllib3, sniffio, pycparser, packaging, idna, h11, charset-normalizer, certifi, aiofiles, requests, httpcore, deprecation, cffi, anyio, requests-toolbelt, httpx, cryptography, jwcrypto, python-keycloak
Successfully installed aiofiles-24.1.0 anyio-4.9.0 async-property-0.2.2 certifi-2025.4.26 cffi-1.17.1 charset-normalizer-3.4.2 cryptography-44.0.3 deprecation-2.1.0 h11-0.16.0 httpcore-1.0.9 httpx-0.28.1 idna-3.10 jwcrypto-1.5.6 packaging-25.0 pycparser-2.22 python-keycloak-5.5.0 requests-2.32.3 requests-toolbelt-1.0.0 sniffio-1.3.1 urllib3-2.4.0
Aggiorna requirements.txt
# pip freeze > requirements.txt
Ora configura un nuovo client library-api nel tuo library-realm tramite la console di amministrazione di Keycloak.

In General Settings:
- Client type:
OpenID Connect - ClientID:
library-api - Name:
Library api - Clicca su
Next

In Capability config:
- Abilita
Client authentication - Abilita
Authorization - In
Authorization flowseleziona:- Standard flow
- OAuth 2.0 Device Authorization Grant
- Clicca su
Next

In Login settings:
- Imposta
Valid redirect URIssu* - Imposta
Web originssu* - Clicca su Save

Nel client library-api apri la scheda Credentials e copia il Client Secret.
Abbiamo configurato il client Keycloak per usare l’introspection.
Panoramica dell’integrazione con Keycloak
Introspection di Keycloak
L’endpoint di introspection di Keycloak permette a un’applicazione di verificare un access token e di ottenere informazioni su di esso.
Perché usare l’introspection?
È un endpoint esposto da Keycloak (conforme allo standard OAuth2) che permette a un’applicazione di inviare un token e di ricevere una risposta che indica se il token è valido, scaduto o revocato, e quali permessi o informazioni sull’utente contiene.
- Perché è utile?
Il backend (l’API Django) riceve spesso richieste con un token. Invece di fidarsi ciecamente del token, può chiedere a Keycloak se è ancora valido e ottenere dettagli come utente, ruoli, scadenza, ecc.
Esempio di flusso:
- L’utente si autentica tramite Keycloak e ottiene un access token.
- L’utente invia il token al backend Django.
- Django chiama l’endpoint di introspection di Keycloak con il token.
- Keycloak risponde con lo stato del token e le informazioni associate.
- Django accetta o rifiuta la richiesta in base alla risposta.
Nota: l’introspection aggiunge una chiamata di rete, che può rallentare leggermente le richieste rispetto alla validazione locale.
Diagramma riassuntivo:
sequenceDiagram
participant Angular App as Angular App
participant Keycloak as Keycloak
participant Django API as Django API
Angular App ->> Keycloak: Authenticate (OIDC)
Keycloak ->> Angular App: Obtain Access Token
loop For Each Request
alt If Token is Active
Angular App ->> Django API: Send Token in API Request
Django API ->> Keycloak: Introspect/Validate Token
alt If Token is Valid
Keycloak ->> Django API: User/Role Info
Django API -->> Django API: Elaborate Data
Django API ->> Angular App: Respond with Data
else If Token is not Valid
Keycloak ->> Django API: Send HTTP ERROR - Invalid Token
Django API ->> Angular App: Send 403 Forbidden to Angular App
end
else If token has expired
Angular App ->> Keycloak: Use Refresh Token to Request new Access Token
Keycloak ->> Angular App: Obtain Access Token
end
end
Legenda:
- Angular App: autentica gli utenti tramite Keycloak e allega l’access token alle richieste API.
- Django API: riceve le richieste, valida i token (usando l’introspection se necessario) e applica i permessi.
- Server Keycloak: gestisce l’autenticazione, emette i token e fornisce le informazioni su utenti e ruoli.
Questo diagramma riassume il flusso di autenticazione e autorizzazione, con Keycloak come identity provider centrale.
Aggiornare le impostazioni di Django
Aggiungi le proprietà di Keycloak al tuo django.env:
KEYCLOAK_SERVER_URL=http://127.0.0.1:8080/
KEYCLOAK_REALM=library-realm
KEYCLOAK_CLIENT_ID=library-api
KEYCLOAK_CLIENT_SECRET_KEY=[UPDATE WITH KEYCLOAK CLIENT SECRET]
In settings.py:
KEYCLOAK_CONFIG = {
'KEYCLOAK_SERVER_URL': django_env('KEYCLOAK_SERVER_URL'),
'KEYCLOAK_REALM': django_env('KEYCLOAK_REALM'),
'KEYCLOAK_CLIENT_ID': django_env('KEYCLOAK_CLIENT_ID'),
'KEYCLOAK_CLIENT_SECRET_KEY': django_env('KEYCLOAK_CLIENT_SECRET_KEY')
}
Ora crea una nuova classe Authentication per gestire e validare i Bearer Token generati da Keycloak.
Scopo di una Authentication Class in Django
Una Authentication Class in Django REST Framework identifica l’utente che effettua una richiesta API analizzando le credenziali (token, header, ecc.) e stabilisce se l’utente è autenticato.
Perché è importante?
- Protegge le API garantendo che solo gli utenti autenticati possano accedere alle risorse.
- Supporta diversi metodi di autenticazione, modificando o aggiungendo Authentication Class.
- Fornisce le informazioni sull’utente alle view e ai controlli dei permessi.
Come funziona?
- Ogni richiesta API passa attraverso la Authentication Class.
- Se sono presenti credenziali valide, alla richiesta viene associato un oggetto utente.
- Se le credenziali mancano o non sono valide, la richiesta viene rifiutata con un errore di autenticazione (HTTP 401 Unauthorized).
Nel nostro caso implementiamo una Authentication Class personalizzata che valida i token di Keycloak tramite introspection, così solo chi possiede un token valido può accedere alle API Django.
Che cos’è un Bearer Token e a cosa serve?
Un Bearer Token è un access token usato per autenticare e autorizzare le richieste a un’API protetta. Chiunque possieda questo token (il “bearer”) può accedere alle risorse protette.
Utilizzo:
- Viene emesso da un sistema di autenticazione (come Keycloak) dopo un login riuscito.
- Viene incluso nell’header
Authorizationdi ogni richiesta HTTP:Authorization: Bearer <token>
- Permette al backend di identificare l’utente e verificarne i permessi.
- È usato comunemente in OAuth 2.0 e OpenID Connect.
Il Bearer Token è la chiave che permette a un client di dimostrare la propria identità e di accedere in modo sicuro alle API protette.
Con queste basi teoriche possiamo ora implementare il codice necessario a far funzionare la nostra applicazione.
Implementare l’autenticazione Keycloak in Django
Implementiamo in Django REST Framework una classe di autenticazione personalizzata che valida i token di Keycloak usando l’endpoint di introspection.
1. Creare la Authentication Class
Crea un nuovo file, ad esempio library_rest/library_rest/authentications.py, nella tua app Django:
from rest_framework import authentication
from rest_framework import exceptions
from keycloak import KeycloakOpenID
import keycloak.exceptions
from django.conf import settings
from datetime import datetime
from django.utils import timezone
import json
from django.contrib.auth.models import AbstractBaseUser
from drf_spectacular.extensions import OpenApiAuthenticationExtension
class KeyCloakAuthenticationSchema(OpenApiAuthenticationExtension):
# full import path OR class ref
target_class = 'IpBlocker.authentication.KeyCloakAuthentication'
name = 'KeyCloakAuthentication' # name used in the schema
def get_security_definition(self, auto_schema):
return {
'type': 'apiKey',
'in': 'header',
'name': 'api_key',
}
class KeyCloakAuthentication(authentication.BaseAuthentication):
def authenticate(self, request):
access_token = request.META.get('HTTP_AUTHORIZATION')
if not access_token:
return None
access_token = access_token.replace("Bearer ", "")
try:
keycloak_openid = KeycloakOpenID(
server_url=settings.KEYCLOAK_CONFIG['KEYCLOAK_SERVER_URL'],
client_id=settings.KEYCLOAK_CONFIG['KEYCLOAK_CLIENT_ID'],
realm_name=settings.KEYCLOAK_CONFIG['KEYCLOAK_REALM'],
client_secret_key=settings.KEYCLOAK_CONFIG['KEYCLOAK_CLIENT_SECRET_KEY']
)
user_info = keycloak_openid.userinfo(
access_token
)
token_info = keycloak_openid.introspect(access_token)
except keycloak.exceptions.KeycloakAuthenticationError:
raise exceptions.AuthenticationFailed('Invalid token')
except keycloak.exceptions.KeycloakGetError as e:
JSON = json.loads(e.response_body.decode('utf8'))
raise exceptions.AuthenticationFailed(
'Keycloak error: {}'.format(JSON['error']))
except keycloak.exceptions.KeycloakConnectionError:
raise exceptions.AuthenticationFailed(
'Keycloak connection error')
# user = User(is_authenticated=True)
class User(object):
pass
user = User()
user.username = user_info['preferred_username']
user.email = user_info['email']
user.first_name = user_info['given_name']
user.last_name = user_info['family_name']
user.is_superuser = False
user.is_staff = False
user.is_active = True
user.is_authenticated = True
user.last_login = timezone.now()
user.user_info = user_info
user.token_info = token_info
return (user, None)
Il codice definisce due classi Python per l’autenticazione tramite Keycloak nella nostra applicazione Django:
1. KeyCloakAuthenticationSchema
- Scopo: estende
OpenApiAuthenticationExtensionper documentare lo schema di autenticazione in OpenAPI/Swagger. - Proprietà:
target_class: punta alla vera classe di autenticazione.name: il nome usato nello schema.
- Metodo
get_security_definition:
Restituisce un dizionario che descrive il tipo di autenticazione comeapiKey, specificando che la chiave si trova nell’header HTTP con il nomeapi_key.
2. KeyCloakAuthentication
- Scopo: estende
authentication.BaseAuthenticationper implementare l’autenticazione tramite Keycloak. - Metodo
authenticate:- Recupera l’access token dall’header
Authorizationdella richiesta. - Se il token non è presente, restituisce
None(nessun utente autenticato). - Rimuove il prefisso “Bearer ” dal token.
- Crea un’istanza di
KeycloakOpenIDusando le impostazioni del file di configurazione. - Recupera da Keycloak le informazioni sull’utente (
userinfo) e sul token (introspect). - Gestisce i vari errori di autenticazione e di connessione, restituendo gli errori appropriati.
- Crea dinamicamente un oggetto
Usere ne popola gli attributi con i dati ottenuti da Keycloak. - Restituisce una tupla
(user, None)come richiesto dal sistema di autenticazione di Django.
- Recupera l’access token dall’header
2. Registrare la Authentication Class
Nel nostro settings.py aggiorna le authentication class del REST framework:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'library_rest.authentications.KeyCloakAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
],
# ... other settings ...
}
Ora dobbiamo assicurarci che un Bearer token venga inviato con le chiamate REST al nostro servizio API ogni volta che una risorsa richiede autenticazione. La libreria keycloak-angular offre già un modo per integrare allo scopo una classe Interceptor.
Che cos’è un Interceptor
Un Interceptor in Angular è una classe che implementa l’interfaccia HttpInterceptor e permette di intercettare e modificare tutte le richieste e risposte HTTP effettuate dall’applicazione. Gli interceptor sono usati comunemente per:
- Aggiungere automaticamente gli header di autenticazione (come il Bearer token) a ogni richiesta API.
- Gestire gli errori HTTP globali.
- Modificare o registrare richieste e risposte.
Nel contesto di keycloak-angular, un interceptor serve a inserire l’access token ottenuto da Keycloak nell’header Authorization di ogni richiesta alle API protette, garantendo che solo gli utenti autenticati possano accedere alle risorse del backend.
Come funziona:
- L’utente effettua il login tramite Keycloak e ottiene un access token.
- Ogni volta che l’applicazione effettua una richiesta HTTP al backend, l’interceptor aggiunge automaticamente l’header
Authorization: Bearer <token>. - Il backend può quindi validare il token e autorizzare l’accesso alle risorse richieste.
Questo approccio rende l’integrazione tra frontend e backend trasparente e sicura.
Modifica app.config.ts come segue:
import { ApplicationConfig, importProvidersFrom, provideZoneChangeDetection } from "@angular/core";
import { provideRouter } from "@angular/router";
import { routes } from "./app.routes";
import { ApiModule, Configuration, ConfigurationParameters } from "./modules/core/api/v1";
import { environment } from "../environments/environment.development";
import { provideHttpClient, withFetch, withInterceptors, withXsrfConfiguration } from "@angular/common/http";
import {
provideKeycloak,
withAutoRefreshToken,
AutoRefreshTokenService,
UserActivityService,
createInterceptorCondition,
IncludeBearerTokenCondition,
INCLUDE_BEARER_TOKEN_INTERCEPTOR_CONFIG,
includeBearerTokenInterceptor,
} from "keycloak-angular";
export function apiConfigFactory(): Configuration {
const params: ConfigurationParameters = {
basePath: environment.api_url,
};
return new Configuration(params);
}
const regex = new RegExp(`^(${environment.api_url})(/.*)?$`, "i");
const urlCondition = createInterceptorCondition<IncludeBearerTokenCondition>({
urlPattern: regex,
bearerPrefix: "Bearer",
});
export const provideKeycloakAngular = () =>
provideKeycloak({
config: {
url: environment.keycloak.url,
realm: environment.keycloak.realm,
clientId: environment.keycloak.client_id,
},
initOptions: {
onLoad: "check-sso",
silentCheckSsoRedirectUri: window.location.origin + "/silent-check-sso.html",
},
features: [
withAutoRefreshToken({
onInactivityTimeout: "logout",
sessionTimeout: 1000 * 60 * 60, // 1 hour
}),
],
providers: [AutoRefreshTokenService, UserActivityService],
});
export const appConfig: ApplicationConfig = {
providers: [
provideKeycloakAngular(),
{
provide: INCLUDE_BEARER_TOKEN_INTERCEPTOR_CONFIG,
useValue: [urlCondition], // <-- Note that multiple conditions might be added.
},
provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(routes),
importProvidersFrom(ApiModule.forRoot(apiConfigFactory)),
provideHttpClient(
withFetch(),
withXsrfConfiguration({
cookieName: "CUSTOM_XSRF_TOKEN",
headerName: "X-Custom-Xsrf-Header",
}),
withInterceptors([includeBearerTokenInterceptor])
),
],
};
const regex = new RegExp(`^(${environment.api_url})(/.*)?$`, "i");
Crea una nuova espressione regolare (regex). L’espressione regolare è pensata per corrispondere a qualsiasi URL che inizi con il valore di environment.api_url, seguito facoltativamente da una barra / e da qualsiasi altra cosa. Il flag ‘i’ rende la ricerca insensibile alle maiuscole/minuscole.
const urlCondition = createInterceptorCondition<IncludeBearerTokenCondition>({
urlPattern: regex,
bearerPrefix: "Bearer",
});
Crea una condizione (urlCondition) per un interceptor (presumibilmente HTTP). Passa un oggetto con due proprietà:
urlPattern: la regex appena creata, usata per identificare gli URL a cui la condizione deve essere applicata.bearerPrefix: la stringa'Bearer', probabilmente usata per aggiungere un token di autenticazione nell’header Authorization delle richieste HTTP.
Questo codice definisce una regola per intercettare tutte le richieste HTTP dirette all’API specificata in environment.api_url e, per queste, applica una logica che probabilmente aggiunge un Bearer token per l’autenticazione.
{
provide: INCLUDE_BEARER_TOKEN_INTERCEPTOR_CONFIG,
useValue: [urlCondition], // <-- Note that multiple conditions might be added.
},
- provide: specifica il token di iniezione (
INCLUDE_BEARER_TOKEN_INTERCEPTOR_CONFIG). Serve a identificare la configurazione che vuoi fornire al sistema di Dependency Injection di Angular. - useValue: qui assegni un valore statico che verrà usato quando qualcuno richiede
INCLUDE_BEARER_TOKEN_INTERCEPTOR_CONFIG. - [urlCondition]: è la nostra espressione regolare che permette di intercettare tutte le chiamate dirette ai nostri servizi Django.
La riga:
withInterceptors([includeBearerTokenInterceptor]);
- withInterceptors: è una funzione che permette di aggiungere uno o più “interceptor” alle richieste HTTP. Un interceptor è un pezzo di codice che può modificare o osservare una richiesta o una risposta prima che venga inviata o ricevuta.
- [includeBearerTokenInterceptor]: è un array contenente un interceptor chiamato
includeBearerTokenInterceptor. Questo interceptor, come suggerisce il nome, aggiunge un token “Bearer” (tipicamente usato per l’autenticazione OAuth2) all’header Authorization di ogni richiesta HTTP.
Ora apri la tua applicazione web e usa la console di debug del browser per ispezionare gli header HTTP inviati nelle richieste alla tua API.
GET /library/books?ordering=title&page=1&page_size=5 HTTP/1.1
Host: 127.0.0.1:8000
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:137.0) Gecko/20100101 Firefox/137.0
Accept: application/json
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br, zstd
Referer: http://127.0.0.1:4200/
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJMUEZvd2RMbFRNUWRoOWhMZjM3ZFk5WUpGYXBEVURnNGE5Q3FUS1VHbkhNIn0.eyJleHAiOjE3NDYzNzE5NTIsImlhdCI6MTc0NjM3MTY1MiwiYXV0aF90aW1lIjoxNzQ2MzcxNjUyLCJqdGkiOiJvbnJ0YWM6NGE3YWYwMzAtYzM2Ny00MjZjLWFhN2EtZmI4MzUzYjQ0ZmE3IiwiaXNzIjoiaHR0cDovLzEyNy4wLjAuMTo4MDgwL3JlYWxtcy9saWJyYXJ5LXJlYWxtIiwiYXVkIjoiYWNjb3VudCIsInN1YiI6ImRjYTI2ZTdjLTVjNmEtNGY3NC1hYjI5LTA5YWI5M2IwZDIwOCIsInR5cCI6IkJlYXJlciIsImF6cCI6ImxpYnJhcnktd2ViIiwic2lkIjoiMTgwYTU1ZDQtZGQ2Zi00NzFhLWJlMGYtMTlhNjJjYjA4MzhjIiwiYWNyIjoiMSIsImFsbG93ZWQtb3JpZ2lucyI6WyIqIl0sInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJkZWZhdWx0LXJvbGVzLWxpYnJhcnktcmVhbG0iLCJvZmZsaW5lX2FjY2VzcyIsInVtYV9hdXRob3JpemF0aW9uIl19LCJyZXNvdXJjZV9hY2Nlc3MiOnsiYWNjb3VudCI6eyJyb2xlcyI6WyJtYW5hZ2UtYWNjb3VudCIsIm1hbmFnZS1hY2NvdW50LWxpbmtzIiwidmlldy1wcm9maWxlIl19fSwic2NvcGUiOiJvcGVuaWQgZW1haWwgcHJvZmlsZSIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwibmFtZSI6IlJpY2NhcmRvIEdpYW5uZXR0byIsInByZWZlcnJlZF91c2VybmFtZSI6ImF4aW9tNCIsImdpdmVuX25hbWUiOiJSaWNjYXJkbyIsImZhbWlseV9uYW1lIjoiR2lhbm5ldHRvIiwiZW1haWwiOiJyZ2lhbm5ldHRvQGdtYWlsLmNvbSJ9.mtCK6Nfff1gozkYsZiicdmSAGrsbL-UJmfLKyL3Nz8PL06m_jxIeSIF0Lc4qTFNTwlpykWemb86kWCgIQp7NjhLBLZXAFwxtcpoI99AdebhlQS5EMhoQrX7A1xENqc9a-aPfOTjbo9jBm_xVLijxJRYolXgbxa8t7NEC7JM5E0vYs52Up5y3gz1uhbz-KRhr1f9BeuwX7P1E6mCHDZxZ13_z4cWlgyycXJhg0JgSCIBPWkLceR59fCYiSC13VoeVoiBTAP8s8NfUEWmCsRpqAK3jb2zd-AHPbrRNdyo9WPyrwz8Uf50FyBtQgywNrKj5blHJee_MJMffSEDyWz0a6A
Origin: http://127.0.0.1:4200
DNT: 1
Sec-GPC: 1
Connection: keep-alive
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
Priority: u=4
Pragma: no-cache
Cache-Control: no-cache
Come possiamo vedere, ora è presente un header Authorization con il Bearer token necessario a validare la nostra identità. Nota che, come richiesto, l’header Authorization è presente solo nelle richieste dirette alla nostra applicazione Django.
Ora la nostra applicazione funziona correttamente.

Lascia un commento