Skip to content

Vipcube/nestjs-keycloak-example

Repository files navigation

Example of Secure NestJS REST API with Keycloak

Description

The example to test how to secure Nest framework API integrate with Keycloak OAuth 2.0.

Installation

$ npm install

Setup Keycloak

  1. Startup Keycloak Server
$ docker-compose -f ./docker/docker-compose.yml up -d 
  1. Change to nodejs-example realm.
  2. Regenerate the client nestjs-app secret.
  3. Update keycloak.json with new generate the client secret.

Example:

{
  "realm": "nodejs-example",
  "auth-server-url": "http://localhost:9003/auth",
  "resource": "nestjs-app",
  "credentials": {
    "secret": "%client-secret%"
  },
  "public-client": false
}

Running the app

$ npm run start

Test with Secure REST API

  1. Get token from Keycloak.
curl --location --request POST 'http://localhost:9003/auth/realms/nodejs-example/protocol/openid-connect/token' \
--header 'Authorization: Basic %BASIC_AUTH_BASE_ON_ID_SECRET%' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=client_credentials'
  1. Test API endpoints.
curl --location --request GET 'http://localhost:3000/users' \
--header 'Authorization: Bearer %TOKEN%'
  1. Test API endpoints secure with resource scopes.
curl --location --request GET 'http://localhost:3000/users/scope' \
--header 'Authorization: Bearer %TOKEN%'

License

Nest is MIT licensed.

About

Example Secure NestJS REST API with Keycloak.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published