Improve security with Keycloak and Spring
Tags: microservices, keycloak, java, spring
Published: 2022-07-10 02:42:26

## Keycloak

An open source Identity and Access Management solution aimed at modern applications and services. It makes it easy to secure applications and services with little to no code, which means that you just need to configure functionalities, don’t need to write code. Therefore it will save development time. As follows, we list some of the great features we can enjoy if we decide to use Keycloak:

- Single sign-on and single sign-out
- Social login
- User federation (LDAP, Active directory, …)
- Centralized management with Admin console
- Standard protocols (OpenID Connect, OAuth2.0, SAML 2.0)
- Password Policies
- Easy setup and integration
- Customizable and extensible
- High performance

## Single-Sign On
Users authenticate with Keycloak rather than individual applications. This means that your applications don't have to deal with login forms, authenticating users, and storing users. Once logged-in to Keycloak, users don't have to login again to access a different application.

This also applied to logout. Keycloak provides single-sign out, which means users only have to logout once to be logged-out of all applications that use Keycloak.

## Identity Brokering and Social Login
Enabling login with social networks is easy to add through the admin console. It's just a matter of selecting the social network you want to add. No code or changes to your application is required.

Keycloak can also authenticate users with existing OpenID Connect or SAML 2.0 Identity Providers. Again, this is just a matter of configuring the Identity Provider through the admin console.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6rpqw7vswvbrci09s8z7.png)

## User Federation
Keycloak has built-in support to connect to existing LDAP or Active Directory servers. You can also implement your own provider if you have users in other stores, such as a relational database.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/paj23t4r0yd97mk0kbhl.png)

## Admin Console
Through the admin console administrators can centrally manage all aspects of the Keycloak server.

They can enable and disable various features. They can configure identity brokering and user federation.

They can create and manage applications and services, and define fine-grained authorization policies.

They can also manage users, including permissions and sessions.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c34lx0yjl3ip4zmu9ni0.png)

## Running and Implementing API Authorization with Keycloak

The following technologies were used to carry out the project and it is necessary to install some items:

- Docker
- Java 17
- Maven
- SpringBoot
- H2
- Postgres
- Pgadmin
- Keycloak

### Preparing Environment

**Running Keycloack with Postgres**

This repository has a docker-compose.yaml file already with the necessary configuration to run Keycloak, Postgres and PgAdmin (Great database manager)

```
docker-compose up -d
```

After running the command, Keycloak will be available on port 8080

```
localhost:8080/auth
```

![login](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pvr8e4vi7fbb9786faxy.png)


The usernames and password were defined in the docker-compose. To authenticate, use the following username and password:

```
KEYCLOAK_USER: admin
KEYCLOAK_PASSWORD: Pa55w0rd
```

## Configuring Keycloak

After installation, we need to configure it inside Keycloak. For this we will access the Clients option and create 2 clients: Spring-boot-Keycloak and Spring-boot-Keycloak-Client.

Below the image with the two configuration examples used.


![Configuration Keycloak](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6qtqxq7blj2h5vap0sds.png)

![Configuration Keycloak](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d7xez0co4i3knftvoxhx.png)
Image

### Spring Implementation Service

The main objective of this documentation is to use keycloak in our requests. Here in this link you will be able to access a repository where you have all the implementation by Java and Spring.

[Here is the complete code of the project](https://github.com/lucasnscr/OpenId-Keycloak-Spring)

### Keycloak and Spring in action

To generate a valid token, we will send a **POST** request to Keycloak.

```
localhost:8080/auth/realms/master/protocol/openid-connect/token
```

Iremos montar o body da nossa requisição no formato: form-urlencoded.

```
username: admin
password: password
client_id: spring-boot-keycloak-client
grant_type: password
```

After the request, we will have a valid token generated by the keycloak. That we will apply in our second request in our service. The token will be in the **access_token** field


![Request example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/akb8hxh0gfxt7mn3rdhj.png)


**Building the request for the Spring service**

When assembling our second request, we will need to inform something extremely important, to consume the data provided by the service, the valid token generated by Keycloak.


For this, we will configure a get request in our postman and in the Authorization part indicate the use of Bearer Token and apply the valid token in the field.

If we do not inform the token, our request will have the status of 401 (Not authorized), however when informing the token we will have a request 200 (OK)


URL for second request **GET**:

```
localhost:9090/users/1
```

![Second Request](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zw2itl10cyrrc120qz1c.png)

Here we come to the end of our security implementation with spring and keycloak.