From the Keycloak website, “Keycloak is an open source identity and access management solution”. Today we’ll look at how to protect your HTTP API with Keycloak.

One of the modern ways to protect an HTTP API today is via the “Authorization: Bearer ” HTTP header and with the token being a JWT carrying the identity and the claims (roles, etc.) of the consumer of the API.

We’ll assume you already have a JS frontend app or at least a HTTP client that performed the authentication against Keycloak and is in possession of a JWT and can pass it as a HTTP “Authorization: Bearer ” header to your NestJS backend.

JWTs can be symmetrically signed (same secret to sign and to verify the JWT) or asymmetrically (token signed with private key and verifiable with the corresponding public key). Keycloak uses the later which is great because it allows multiple backends to be able to verify JWTs without disseminating a secret across multiple services. It means that if one of your service is compromised, at least an attacker won’t be able to forge JWTs on its own to attack other services.


Implementation

We need to write a Guard that will decorate the controllers or the individual handlers that we want to protect.

This guard will use an AuthenticationService which will perform (in various ways as you’ll see below) the verification of the JWT.

All the required services will be part of an AuthenticationModule that will export some of them that may be required by the rest of your application.

We’ll provide a working implementation and refine it later to make it more practical to use in production, in E2E tests, etc.

#nestjs #nodejs #software-development #tutorial #typescript

Protecting your NestJS API with Keycloak
40.25 GEEK