Panduan Cepat untuk Menggunakan Keycloak dengan Spring Boot

1. Ikhtisar

Dalam artikel ini, kami akan membahas dasar-dasar menyiapkan server Keycloak, cara menghubungkan aplikasi Spring Boot, dan cara menggunakannya dengan Spring Security .

2. Apa Itu Keycloak?

Keycloak adalah solusi Manajemen Identitas dan Akses sumber terbuka yang ditargetkan untuk aplikasi dan layanan modern.

Keycloak menawarkan fitur-fitur seperti Single-Sign-On (SSO), Identity Brokering and Social Login, User Federation, Client Adapters, Admin Console, dan Account Management Console. Untuk mempelajari lebih lanjut tentang Keycloak, silakan kunjungi halaman resmi.

Dalam tutorial kami, kami akan menggunakan Konsol Admin Keycloak untuk menyiapkan dan kemudian menghubungkan ke Spring Boot menggunakan Adaptor Klien Keycloak.

3. Menyiapkan Server Keycloak

3.1. Mendownload dan Menginstal Keycloak

Ada beberapa distribusi untuk dipilih.

Namun, dalam tutorial ini, kami akan menggunakan versi mandiri.

Mari unduh distribusi server Keycloak-11.0.2 Standalone dari sumber resminya.

Setelah kami mengunduh distribusi server Standalone, kami dapat mengekstrak dan memulai Keycloak dari terminal:

unzip keycloak-11.0.2.zip cd keycloak-11.0.2/bin ./standalone.sh -Djboss.socket.binding.port-offset=100

Setelah menjalankan ./standalone.sh , Keycloak akan memulai layanannya. Begitu kita melihat baris yang berisi Keycloak 11.0.2 (WildFly Core 12.0.3.Final) dimulai , kita akan tahu bahwa permulaannya telah selesai.

Sekarang buka browser dan kunjungi // localhost: 8180. Kami akan diarahkan ke // localhost: 8180 / auth untuk membuat login administratif:

Mari buat pengguna admin awal bernama inisial1 dengan kata sandi zaq1! QAZ . Saat mengklik Buat , kita akan melihat pesan Dibuat Pengguna .

Sekarang kita dapat melanjutkan ke Konsol Administratif. Di halaman login, kita akan memasukkan kredensial pengguna admin awal:

3.2. Menciptakan Realm

Login yang berhasil akan membawa kita ke konsol dan membuka alam Master default untuk kita.

Di sini kita akan fokus pada pembuatan ranah kustom.

Menavigasi Mari kita ke sudut kiri atas untuk menemukan Tambah ranah tombol :

Di layar berikutnya, mari tambahkan ranah baru bernama SpringBootKeycloak :

Setelah mengklik tombol Buat , ranah baru akan dibuat dan kita akan diarahkan ke sana. Semua operasi di bagian selanjutnya akan dilakukan di ranah SpringBootKeycloak baru ini .

3.3. Membuat Klien

Sekarang kita akan menavigasi ke halaman Klien. Seperti yang bisa kita lihat pada gambar di bawah, Keycloak hadir dengan Klien yang sudah ada di dalamnya :

Tapi kita perlu menambahkan klien baru ke aplikasi kita, jadi kita akan mengklik Buat . Kami akan memanggil aplikasi masuk Klien baru :

Di layar berikutnya, untuk tutorial ini, kami akan meninggalkan semua default kecuali bidang Valid Redirect URIs . Bidang ini harus berisi URL aplikasi yang akan menggunakan klien ini untuk otentikasi :

Nanti, kami akan membuat Aplikasi Spring Boot yang berjalan di port 8081 yang akan menggunakan klien ini. Karenanya kami telah menggunakan URL redirect // localhost: 8081 / * di atas.

3.4. Membuat Peran dan Pengguna

Keycloak menggunakan Akses Berbasis Peran. Oleh karena itu, setiap pengguna pasti memiliki peran.

Untuk melakukan itu, kita perlu menavigasi ke halaman Peran :

Kemudian, kami akan menambahkan peran pengguna :

Now we've got a role that can be assigned to users, but there are no users yet. So let's go the Users page and add one:

We'll add a user named user1:

Once the user is created, a page with its details will be displayed:

We can now go to the Credentials tab. We'll be setting the initial password to [email protected]:

Finally, we'll navigate to the Role Mappings tab. We'll be assigning the user role to our user1:

4. Generating Access Tokens with Keycloak's API

Keycloak provides a REST API for generating and refreshing access tokens. We can easily use this API to create our own login page.

First, we need to acquire an access token from Keycloak by sending a POST request to this URL:

//localhost:8180/auth/realms/master/protocol/openid-connect/token

The request should have this JSON body:

{     'client_id': 'your_client_id', 'username': 'your_username', 'password': 'your_password', 'grant_type': 'password' }

In response, we'll get an access_token and a refresh_token.

The access token should be used in every request to a Keycloak-protected resource by simply placing it in the Authorization header:

headers: {     'Authorization': 'Bearer' + access_token }

Once the access token has expired, we can refresh it by sending a POST request to the same URL as above, but containing the refresh token instead of username and password:

{     'client_id': 'your_client_id', 'refresh_token': refresh_token_from_previous_request, 'grant_type': 'refresh_token' }

Keycloak will respond to this with a new access_token and refresh_token.

5. Creating a Spring Boot Application

5.1. Dependencies

The latest Spring Boot Keycloak Starter dependencies can be found on Maven Central.

The Keycloak Spring Boot adaptercapitalizes on Spring Boot’s auto-configuration, so all we need to do is add the Keycloak Spring Boot starter to our project.

Within the dependencies XML element, we need the following to run Keycloak with Spring Boot:

 org.keycloak keycloak-spring-boot-starter  

After the dependencies XML element, we need to specify dependencyManagement for Keycloak:

   org.keycloak.bom keycloak-adapter-bom 11.0.2 pom import   

The following embedded containers are supported now and don't require any extra dependencies if using Spring Boot Keycloak Starter:

  • Tomcat
  • Undertow
  • Jetty

5.2. Thymeleaf Web Pages

We're using Thymeleaf for our web pages.

We've got three pages:

  • external.html – an externally facing web page for the public
  • customers.html – an internally facing page that will have its access restricted to only authenticated users with the role user.
  • layout.html – a simple layout, consisting of two fragments, that is used for both the externally facing page and the internally facing page

The code for the Thymeleaf templates is available on Github.

5.3. Controller

The web controller maps the internal and external URLs to the appropriate Thymeleaf templates:

@GetMapping(path = "/") public String index() { return "external"; } @GetMapping(path = "/customers") public String customers(Principal principal, Model model) { addCustomers(); model.addAttribute("customers", customerDAO.findAll()); model.addAttribute("username", principal.getName()); return "customers"; }

For the path /customers, we're retrieving all customers from a repository and adding the result as an attribute to the Model. Later on, we iterate through the results in Thymeleaf.

To be able to display a username, we're injecting the Principal as well.

Note that we're using customer here just as raw data to display, and nothing more.

5.4. Keycloak Configuration

Here's the basic, mandatory configuration:

keycloak.auth-server-url=//localhost:8180/auth keycloak.realm=SpringBootKeycloak keycloak.resource=login-app keycloak.public-client=true 

As we recall, we started Keycloak on port 8180, hence the path specified in keycloak.auth-server-url. We enter the realm name we created in the Keycloak admin console.

The value we specify in keycloak.resource matches the client we named in the admin console.

Here are the security constraints we'll be using:

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

These constraints ensure that every request to /customers/* will only be authorized if the one requesting it is an authenticated user with the role user.

Additionally, we can define keycloak.principal-attribute as preferred_username so as to populate our controller's Principal with a proper user:

keycloak.principal-attribute=preferred_username

5.5. Demonstration

Now, we're ready to test our application. To run a Spring Boot application, we can start it easily through an IDE like Spring Tool Suite (STS) or run this command in the terminal:

mvn clean spring-boot:run

On visiting //localhost:8081 we see:

Now we click customers to enter the intranet, which is the location of sensitive information.

We can see that we've been redirected to authenticate through Keycloak to see if we're authorized to view this content:

Once we log in as user1, Keycloak will verify our authorization – that we have the user role – and we'll be redirected to the restricted customers page:

Now we've finished the set up of connecting Spring Boot with Keycloak and demonstrating how it works.

As we can see, the entire process of calling the Keycloak Authorization Server was handled seamlessly by Spring Boot for us. We did not have to call the Keycloak API to generate the Access Token ourselves, or even send the Authorization header explicitly in our request for protected resources.

Next, we'll be reviewing how to use Spring Security in conjunction with our existing application.

6. Spring Security

There is a Keycloak Spring Security Adapter, and it’s already included in our Spring Boot Keycloak Starter dependency. We'll now see how to integrate Spring Security with Keycloak.

6.1. Dependency

To use Spring Security with Spring Boot, we must add this dependency:

 org.springframework.boot spring-boot-starter-security 2.2.6.RELEASE 

The latest Spring Boot Starter Security release can be found on Maven Central.

6.2. Configuration Class

Keycloak provides a KeycloakWebSecurityConfigurerAdapter as a convenient base class for creating a WebSecurityConfigurer instance.

This is helpful because any application secured by Spring Security requires a configuration class that extends WebSecurityConfigurerAdapter:

@Configuration @EnableWebSecurity @ComponentScan(basePackageClasses = KeycloakSecurityComponents.class) class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter { @Autowired public void configureGlobal( AuthenticationManagerBuilder auth) throws Exception { KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider(); keycloakAuthenticationProvider.setGrantedAuthoritiesMapper( new SimpleAuthorityMapper()); auth.authenticationProvider(keycloakAuthenticationProvider); } @Bean public KeycloakSpringBootConfigResolver KeycloakConfigResolver() { return new KeycloakSpringBootConfigResolver(); } @Bean @Override protected SessionAuthenticationStrategy sessionAuthenticationStrategy() { return new RegisterSessionAuthenticationStrategy( new SessionRegistryImpl()); } @Override protected void configure(HttpSecurity http) throws Exception { super.configure(http); http.authorizeRequests() .antMatchers("/customers*") .hasRole("user") .anyRequest() .permitAll(); } }

In the code above, the method configureGlobal() tasks the SimpleAuthorityMapper to make sure roles are not prefixed with ROLE_.

Another method, keycloakConfigResolver defines that we want to use the Spring Boot properties file support instead of the default keycloak.json.

Because we've set up the security constraints with Spring Security, we can remove or comment these security constraints we'd placed earlier in the properties file:

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

Now, after we authenticate, we'll be able to access the internal customers' page, same as we saw before.

7. Conclusion

In this tutorial, we’ve configured a Keycloak server and used it with a Spring Boot Application.

Kami juga telah melihat cara menyiapkan Keamanan Musim Semi dan menggunakannya bersama dengan Keycloak. Versi yang berfungsi dari kode yang ditunjukkan dalam artikel ini tersedia di Github.