# Keycloak

## About

An open source solution to provide an Authentication & Authorization.

Easy to use and to flexible enough to integrate with Web and services applications.

{% hint style="info" %}
Usually used as the Identity and Authentication Microservice.
{% endhint %}

### Main Characteristics

* **Multi-plataform support**.
* **Integration with multiple identity providers**, like LDAP, Microsoft Active Directory, Google, Facebook, etc.
* **Centralized administration:** It offers a Centralized Administration Console that allows you to manage users, groups, clients and other security resources.
* **API protection:** It can protect APIs with Access Tokens based on OAuth 2.0 and OpenID Connect.
* **Login personalization:** Allows users to personalize Login pages and use own themes.
* **Multi-tenancy support:** It supports the separation of data and configurations for different Clients and Organizations.
* **DevOps integration:** It can be easily integrated with DevOps tools like Docker and Kubernets.
* **Extensability:** Keycloack is highly extensible with plugins.
* **Highly scalable:** It can deal with huge traffic volumes and users.

### Main Functionalities

* **User Authentication:** Allows that users authenticate in different Apps, with different authentication methods, like `Login & Password`, `Multi Factor`, `SSO`, etc.
* **User Management:** Gives you an Admin console to manage Users, Roles and Permissions, check Activity Logs.
* **User Authorization:** Allows Admins to configure Authorization policies to restrict access to specific resources based on Roles and Permissions.
* **Integration with different Authentication & Authorization protocols** like OAuth 2.0, OpenID Connect and SAML 2.0.
* **Flexible configuration:** It offers a vast varietyof configurations that can be personalized.
* **Session management:** It gives you resources to manage user sessions, including expiration control, renew and ending of sessions.
* **Level based Authentication & Authorization:** Allows Admins to configure different levels policies, using App, User Groups, Roles or Permissions.

## Using It

### Realms

Create Realms to separate Users from the Admin Keycloak console, from Users that are from other Organizations/Services.

{% hint style="info" %}
A `master` Realm is created by default.
{% endhint %}

The idea would be create a new Realm for a new system or group of systems that should share the same user identities.

### Clients

Clients are systems that will be using Keycloak to authenticate users. *(Like login pages, services, etc)*

### Generating Tokens

#### Access Token

Generate an `Access_Token` for a User through the Keycloak API by hitting:

{% hint style="danger" %}
This Token doesn't represent the Authentication done, **but the Authorization on the User's behalf granted to an application**.

This Token is the one informed for subsequent uses, on the API for example, to consume services.
{% endhint %}

{% hint style="danger" %}
Have in mind that this Token can become very large, if there are a lot of Authorization Rules, and this can impact latency of the requests.
{% endhint %}

{% hint style="warning" %}
Keycloak don't use `Content-Type: application/json`.
{% endhint %}

```http
POST http://localhost:8080/realms/realm-name/protocol/openid-connect/token
Content-Type: application/x-www-form-urlencoded
username=<username>&password=<userpassword>&grant_type=password&client_id=<client-id>
```

Where `grant_type` is how the user is authenticating, a configuration from `OAuth2`, and `client_id` is the `ID` of the configured `Client` on Keycloak Admin console.

This request returns:

| Properties                  | Description                                          |
| --------------------------- | ---------------------------------------------------- |
| `access_token`              | A token with following properties.                   |
| `body` `sub`                | User's ID.                                           |
| `body` `realms_access`      | Roles the User has access in the Realm.              |
| `body` `email_verified`     | Stating if User email was verified.                  |
| `body` `preferred_username` | User's username.                                     |
| `body` `given_name`         | User's first name.                                   |
| `body` `family_name`        | User's last name.                                    |
| `body` `email`              | User's email.                                        |
| `refresh_token`             | For refreshing the token when it is about to expire. |
| others...                   |                                                      |

#### ID Token

By default the request for `access_token` don't include the `id_token`. To request it add this to the `HTTP` request.

{% hint style="warning" %}
Sometimes the detailed information about the Authenticated User, is not on the `access_token`.

This may happen to decrease the `access_token` size, or for other reasons.

In Keycloak, by default, all User information here IS in `access_token`.
{% endhint %}

{% hint style="danger" %}
Don't send this `id_token` for subsequent requests, send the `access_token`.
{% endhint %}

```http
POST http://localhost:8080/realms/realm-name/protocol/openid-connect/token
Content-Type: application/x-www-form-urlencoded
username=<username>
&password=<userpassword>
&grant_type=password
&client_id=<client-id>
&scope=openid
```

The request return the same as above, with the addition of the `id_token`:

| Properties                  | Description                                      |
| --------------------------- | ------------------------------------------------ |
| `id_token`                  | The Authentication token with bellow properties. |
| `body` `sub`                | User's ID.                                       |
| `body` `email_verified`     | Stating if User email was verified.              |
| `body` `preferred_username` | User's username.                                 |
| `body` `given_name`         | User's first name.                               |
| `body` `family_name`        | User's last name.                                |
| `body` `email`              | User's email.                                    |

## Authentication Flows

### Authorization Code

Used specialy for Web applications (SPA, Mobile or Server Side), where the Keycloak Login Form is shown to the User for authentication.

{% hint style="danger" %}
There are some vulnerabilities involving this method.
{% endhint %}

<img src="https://1707169559-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FImMH4C6pDnHlHVuDgfGe%2Fuploads%2FTULqGdX3JKSt5aD4i75Y%2Ffile.excalidraw.svg?alt=media&#x26;token=98096af3-3162-4b67-9456-d1c6ae69f997" alt="" class="gitbook-drawing">
