[JAVA] Try using OpenID Connect with Keycloak (Spring Boot application)

Overview

Day 3 of the Keycloak Advent Calendar describes the steps to ** delegate authentication for Spring Boot-based web applications to Keycloak **. Keycloak has an adapter for Spring Boot that makes it easy to secure Spring Boot-based web applications. This makes it a secure Spring Boot application that supports the latest authentication protocol ** "OpenID Connect" ** (OIDC).

Once linked, users will become OIDC's "End User", Spring Boot-based web applications will become OIDC's "Relying Party", and Keycloak will become OIDC's "OpenID Provider".

env.png

Before you start

Before you start working with this tutorial, you need to complete Keycloak setup and create an admin user. Please refer to the article Keycloak Advent Calendar Day 2 to carry out those tasks. Also, Gradle or Maven will be used to build and launch the web application, so please install either one.

This time, we will build both Keycloak and Spring Boot-based web application on localhost.

Cooperation procedure

The procedure for cooperation is as follows. After this is completed, check the operation.

  1. Keycloak settings --1.1. Creating a realm --1.2. Creating a client --1.3. Creating a role --1.4. Creating users and assigning roles
  2. Create a simple Spring Boot application --2.1. Creating an app template with Spring Initializr --2.2. Creating classes and html --2.3. Setting of Keycloak linkage of application

1.1. Creating a realm

Before we create a realm, let's take a brief look at it. ** "Realm" in Keycloak means a range for grouping users, roles, connected datastores (LDAP, etc.). ** Users can create in the realm, and the authentication method etc. can be defined for each realm. By default, there is one realm called "Master", and you can manage all the realms you add afterwards. The "Master" realm is the highest level in the realm hierarchy and can be managed by a super administrator (the administrator account created during initial setup).

realm.png

You can use the "Master" realm to manage users, etc., but basically it is recommended to create a realm, so create a realm first. You can also delete the "Master" realm.

Go to [http: // localhost: 8080 / auth / admin /](http: // localhost: 8080 / auth / admin /) and log in to the Keycloak admin console with an administrator account.

2017-10-29 11.34.Screenshot from 04.png

Click Add Realm in the drop-down menu labeled Master in the top corner on the left.

2017-11-04 01.03.Screenshots from 23.png

The Add Realm page opens. A new realm will be created, so enter "demo" as the realm name and click the "Create" button.

2017-11-04 01.07.Screenshots from 14.png

When you create a realm, you will be taken to the main page of the management console. The current realm should be "demo".

2017-11-04 01.10.Screenshots from 35.png

You can switch between the master realm under your control and the realm you just created by clicking the drop-down menu in the upper left corner.

1.2. Creating a client

Next, create a client (*). In this case, the client is the "Relying Party" defined by OIDC (also called the "client" in OAuth 2.0, which is the basis of OIDC 1.0), and is the Spring Boot application.

* To be precise, create a client profile. The client itself is created using "Spring Initializr" described later.

Click Client on the left menu bar. The client list screen will be displayed, so click the "Create" button.

2017-11-05 20.25.Screenshots from 52.png

Type "sample-app" and click the "Save" button.

2017-11-05 20.26.Screenshot from 06.png

Enter http: // localhost: 8081 / hello for the Valid Redirect URI.

Screenshot from 2017-11-30 21-26-28.png

<!-![Screenshot from 2017-11-05 20.27.19.png](https://qiita-image-store.s3.amazonaws.com/0/43869/9f17916d-8ca3-3e59-b85f- ce215ea23c75.png) |

2017-11-05 20.27.Screenshots from 19.png

-->

1.3. Creating a role

Next, create a role to assign to the user. We'll configure it later so that only users assigned this role can access the Spring Boot application.

The

role means the role of the user and is used to identify the type and category of the user. Administrators, users, managers, employees, etc. are typical roles that exist within an organization. Applications often assign access to specific roles rather than individual users so that it is not difficult to manage users. </ td> </ tr> </ table>

Click Roles in the left menu bar. The role list screen will be displayed, so click the "Create" button.

2017-11-05 20.34.Screenshot from 06.png

Enter "user" in the "Role Name" and click the "Save" button.

2017-11-05 20.34.Screenshots from 29.png

1.4. Creating Users and Assigning Roles

Finally, create a user and assign a role. Click Users in the left menu bar. The user list screen will be displayed, so click the "Create" button.

The user list page opens. Click Add User to the right of the empty user list.

2017-11-04 01.36.Screenshots from 39.png

Enter only the required user name and click the "Save" button to open the new user management page.

2017-11-04 01.38.Screenshots from 12.png

Next, set a password for the new user. Click the Credentials tab.

After entering your new password and password (confirm), you will see a red "Reset Password" button. At this time, change "temporary" to "off". This eliminates the need to change your password the first time you log in.

2017-11-04 11.37.Screenshot from 09.png

Click the "Reset Password" button to reset your password.

Finally, click the "Role Mapping" tag and move ʻuser` under "Available Roles" to "Assigned Roles".

2017-11-05 21.48.Screenshot from 03.png

This completes the Keycloak settings.

2.1. Creating an app template with Spring Initializr

Next, create a Spring Boot application. Use Spring Initializr to create a template for your Spring Boot application. Please visit the Spring Initializr page.

2017-11-05 20.42.Screenshots from 16.png

Enter and select the following as shown in the screen above, and then click the "Generate Project" button.

item Set value
Project Gradle Project or Maven Project
language Java
Dependencies Web、Thymeleaf、DevTools、Keycloak
Group com.example
Artifact sample-app

The compressed file will be downloaded, so unzip it to a suitable directory.

2.2. Creating classes and html

First, create static HTML for the top page. Create an HTML file called ʻindex.html in src / main / resources / static / `with the following contents.

<html>
<head>
    <title>Sample Application</title>
</head>
 <body>
   <h1>Sample Application</h1>
   <a href="/hello">Go to hello page!</a>
 </body>
</html>

Next, create the controller and screen that will be called from this screen. The controller should have the following contents in src / main / java / com / example / sampleapp / with the file name HelloController.java.

package com.example.sampleapp;

import java.util.Locale;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
class HelloController {

    @RequestMapping(value = "/hello")
    public ModelAndView hello(HttpSession ses, ModelAndView mav, Locale locale) {
    	mav.setViewName("hello");
        mav.addObject("message", "Hello! Spring Boot and Keycloak!");
        return mav;
    }
    
    @RequestMapping(value = "/logout")
    public String logout(HttpServletRequest request) throws ServletException {
       request.logout();
       return "redirect:/";
    }
}

The screen called from this controller is created in src / main / resources / templates / with an HTML file called hello.html.

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" th:with="lang=${#locale.language}" th:lang="${lang}">
<h1>Hello</h1>
<p th:text="${message}" /><br />
<p>
    <a href="/logout">Logout</a>
</p>
</html>

The directory structure is as follows.

2017-11-05 21.02.14 からのスクリーンショット.png

This completes the sample web application.

2.3. Setting up Keycloak integration for apps

Finally, configure the created Web application to work with Keycloak. Add the following definition to /src/main/resources/application.properties.

keycloak.auth-server-url=http://localhost:8080/auth
keycloak.realm=demo
keycloak.public-client=true
keycloak.resource=sample-app
keycloak.security-constraints[0].authRoles[0]=user
keycloak.security-constraints[0].securityCollections[0].patterns[0]=/hello/
server.port=8081

It defines that access to [http: // localhost / hello /](http: // localhost / hello /) and below requires authentication and that user must have the role "user". The last property specifies that this application will be listened on on port 8081.

This completes all the settings.

Operation check

Let's check the operation. Start the web application created by the following command.

For Gradle

$ gradle bootRun

For Maven

$ mvn spring-boot:run

When you access [http: // localhost: 8081](http: // localhost: 8081), you will see the following screen.

2017-11-05 22.10.Screenshot from 02.png

Clicking the "Go to hello page!" Link will redirect you to the Keycloak login screen.

2017-11-05 22.04.Screenshots from 53.png

Please log in as the created user. If the settings so far are done properly, the following screen will be displayed.

2017-11-05 22.11.Screenshots from 56.png

Finally

It's very easy to delegate authentication for Spring Boot-based web applications to Keycloak like this. Not only is it easy, but it also implements a standard and secure login process.

I used the Spring Boot Adapter this time, but there is also a Spring Security Adapter, which is included in the Spring Boot Keycloak Starter. I'll talk about this at another time (if there is one ...).


Reference material

mark.png

Recommended Posts