Easily secure your Spring Boot applications with Keycloak

Tech Geek
6 min readNov 22, 2018

--

What is keycloak ?

Security is a crucial aspect of any application, its implementation can be difficult. Keycloak is open source authentication server ( as per the official docs of the keycloak ).

Keycloak is more than just an authentication server, it also provides a complete Identity Management system.

Spring Boot and Keycloak

Keycloak provides adapters for an application that needs to interact with a Keycloak instance. There are adapters for WildFly/EAP, NodeJS, Javascript and of course for Spring Boot.

Setting up a Keycloak server:

You have different options to set up a Keycloak server but the easiest one is probably to grab a standalone distribution, unzip it.

https://www.keycloak.org/downloads.html

You have different options to set up a Keycloak server but the easiest one is probably to grab a standalone distribution, unzip it.

Open a terminal and go to your unzipped Keycloak server and from the bin directory simply run:

./standalone.sh

Then open a browser and go to http://localhost:8080/auth.

Since it’s the first time that the server runs you will have to create an admin user, so let’s create an admin user with admin as username and admin for the password.

Now you can log in into your administration console and start configuring Keycloak.

Creating a new Realm
Keycloak defines the concept of a realm in which you will define your clients, which in Keycloak terminology means an application that will be secured by Keycloak, it can be a Web App, a Java EE backend, a Spring Boot etc.

So let’s create a new realm by simply clicking the “Add realm” button:

Let’s call it “SpringBoot”.

Creating the client, the role, and the user
Now we need to define a client, which will be our Spring Boot app. Go to the “Clients” section and click the “create” button. We will call our client “product-app”:

On the next screen, we can keep the defaults settings but just need to enter a valid redirect URL that Keycloak will use once the user is authenticated. Put as value: “http://localhost:8081/*

Don’t forget to Save!

Now, we will define a role that will be assigned to our users, let’s create a simple role called “user”:

And at last but not least let’s create a user, only the username property is needed, let’s call him “testuser”:

And finally, we need to set his credentials, so go to the credentials tab of your user and choose a password, I will be using “password” , make sure to turn off the “Temporary” flag unless you want the user to have to change his password the first time he authenticates.

Now proceed to the “Role Mappings” tab and assign the role “user”:

We are done for now with the Keycloak server configuration and we can start building our Spring Boot App!

Creating a simple app

Let’s create a simple Spring Boot application, you might want to use the Spring Initializr and choose the following options:

Web
Freemarker
Keycloak
Name your app “product-app” and download the generated project:

https://start.spring.io/

Import the application in your favorite IDE/editor, I will be using Sublime.

Our app will be simple and will contain only 2 pages:

1 An index.html which will be the landing page containing just a link to the product page.
2 Products.ftl which will be our product page template and will be only accessible for authenticated user.

Let’s start by creating in simple index.html file in “/src/resources/static”:

<html>
<head>
<title>My awesome landing page</title>
</head>
<body>
<h1>Landing page</h1>
<a href=”/products”>My products</a>
</body>
</html>

Now we need a controller:

@Controller
class ProductController {
@Autowired ProductService productService;@GetMapping(path = “/products”)
public String getProducts(Model model){
model.addAttribute(“products”, productService.getProducts());
return “products”;
}
@GetMapping(path = “/logout”)
public String logout(HttpServletRequest request) throws ServletException {
request.logout();
return “/”;
}
}

As you can see, it’s simple; we define a mapping for the product page and one for the logout action. You will also notice that we are calling a “ProductService” that will return a list of strings that will put in our Spring MVC Model object, so let’s create that service:

@Component
class ProductService {
public List<String> getProducts() {
return Arrays.asList(“iPad”,”iPod”,”iPhone”);
}
}

We also need to create the products.ftl template, create this file in “src/resources/templates”:

<#import “/spring.ftl” as spring>
<html>
<h1>My products</h1>
<ul>
<#list products as product>
<li>${product}</li>
</#list>
</ul>
<p>
<a href=”/logout”>Logout</a>
</p>
</html>

Here we simply iterate through the list of products that are in our Spring MVC Model object and we add a link to log out from our application.

All that is the left is adding some keycloak properties in our application.properties.

Defining Keycloak’s configuration
Some properties are mandatory:

keycloak.auth-server-url=http://localhost:8080/auth
keycloak.realm=springboot
keycloak.public-client=true
keycloak.resource=product-app

Then we need to define some Security constraints as you will do with a Java EE app in your web.xml:

keycloak.security-constraints[0].authRoles[0]=user
keycloak.security-constraints[0].securityCollections[0].patterns[0]=/products/*

Here, we simply define that every request to /products/* should be done with an authenticated user and that this user should have the role “user”.

One last property is to make sure our application will be running on port 8081:

server.port=8081

We are all set and we can run our app!

You have several options to run your Spring Boot application, with Maven you can simply do:

mvn clean spring-boot:run

Now browse to “http://localhost:8080” and you should see the landing page, click the “products” links and you will be redirected to the Keycloak login page:

Login with our user “testuser/password” and should be redirected back to your product page:

Congratulations! You have secured your first Spring Boot app with Keycloak.

Conclusion

We saw in this article how to deploy and configure a Keycloak Server and then secure a Spring Boot app.

--

--

Tech Geek
Tech Geek

Written by Tech Geek

I’m a software developer from India, currently working with blockchain.

Responses (4)