By Marone: April 2020

How to secure Spring boot
with Keycloak


In this article we are going to secure a Spring boot REST API with keycloak using Resource Owner Password Credentials Grant in short password grant

keycloak password grant

1.The end user johndoe passes the username and password to the client.
2. The client sends the credentials to keycloak.
3. If everything is fine keycloak returns an Access Token.
4. The client use the Access Token to call the API

Warning! The resource owner password credentials grant type is suitable in cases where the resource owner has a trust relationship with the client, such as the device operating system or a highly privileged (RFC 6749)

Used technologies

Keycloak 8.0.1
Java 11
curl 7.65
jq 1.5


Spring security configuration

The root url / is allowed by anyone.
Other urls are allowed by any authenticated user.



Let's test

The url http://localhost:8080 is accessible by all users while /protected and /admin required users to be authenticated.
Calling the /protected without anything returns "status":403,"error":"Forbidden","message":"Access Denied"

Let's test with access token

Since the user johndoe is now authenticated, we are able to access the api.


The complete code can be found in GitHub