springboot integration keycloak

1. Keycloak What is that?

Keycloak is a modern-oriented applications and services of open source IAM (Identity and Access Management) solution.

Keycloak provides single sign-on (SSO), Identity Brokering and social characteristics account login, User Federation, client adapters, management console and account management consoles. For more information about Keycloak, please visit the official page .

In this tutorial, we will use Keycloak management console to configure, and then use the Spring Boot application Keycloak Client Adapter and Keycloak server connected.

2. Install a Keycloak server configuration

1. The mounting portion of the reference keycloak9.0.2 integrated standalone mode mysql8

2. Create a Realm

Let us move the mouse to navigate to the top left corner, find the "Add Realm" button:

We named it " SpringBoot ":

3. Create a client

We need to add a client application, so we click on "Create". We configured the new Client ID as " Product-App ":

On the next page, for the purposes of this tutorial, in addition to "Valid Redirect URIs field", we will keep all the default values. After the configuration, you will be redirected to port 8081 :

Click Save

4. Create a user role and

Keycloak using Role-Based Access. Therefore, each user must have a role.
We need to navigate to the "Role" page:

Then, we add " the User " role:

Now that we have a role can be assigned to users, but there is not a user. So let's go to the new "Users" page with:

We create user "user1":

Once the user is created, the user information will show here:

Enter "Credentials" tab, and the password is " 123456" , pay attention to close Temporary , click Reset Password:

Navigate to the "Role Mappings" tab and assign user roles:

3. Create a Spring Boot application

In order to protect the Spring Bootapplication, you must Keycloak Spring Bootadd the adapter JAR to your application. Then, you have to through the normal Spring Bootconfiguration ( application.propertiesto provide some additional configuration). Let's look at these steps.

1. Official documents Reference

Keycloak Spring BootAdapter takes advantage of Spring Bootthe auto-configuration feature, so you have to do is to Keycloak Spring Bootadd the starter to your project.

To use Maven to add it, add the following to your dependencies in:

<dependency>
    <groupId>org.keycloak</groupId>
    <artifactId>keycloak-spring-boot-starter</artifactId>
</dependency>

Add adapter BOM dependencies:

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.keycloak.bom</groupId>
      <artifactId>keycloak-adapter-bom</artifactId>
      <version>9.0.2</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

The above is the official reference materials

Creating a springbootsimple project include the following jar package

  • Web
  • Freemarker
  • Keycloak

2. Create a project springboot

The final pom.xmldocument is as follows

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>keycloak-study</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>keycloak-study</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.keycloak.bom</groupId>
                <artifactId>keycloak-adapter-bom</artifactId>
                <version>9.0.2</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-spring-boot-starter</artifactId>
            <version>9.0.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Our application will be relatively simple, containing only two pages:

  • A index.html, it will be the login page, which contains only links to product pages.
  • product.ftl, It will be our product page template, and can only be accessed by the user authentication.

First, we create a simple in "/ src / resources / static" directory in the index.htmlfile:

<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:

package com.example.keycloakstudy.controller;

import com.example.keycloakstudy.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

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

@Controller
class ProductController {

    @Autowired
    ProductService productService;

    @GetMapping(path = "/products")
    public String getProducts(Model model){
        model.addAttribute("products", productService.getProducts());
        return "product";
    }

    @GetMapping(path = "/logout")
    public String logout(HttpServletRequest request) throws ServletException {
        request.logout();
        return "/";
    }
}

You will find that this is simply that defines a mapping product page, and then define a mapping for the cancellation of the operation. You will also notice that we call a "ProductService", it will return a list of strings, we put this list into Spring MVC Model objects to go inside, so we have to create the service:

package com.example.keycloakstudy.service;

import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

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

We also need to create product.ftla template. To create this file in the "src / resources / templates" in:

<#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 traverse the Spring MVC Modellist of products subject, and add a log out from our application link.

3. springboot configuration keycloak

We need to do is to application.properties add some of the keycloakrelated properties.

Some properties are a must have:

# keycloak安装服务器的IP和端口
keycloak.auth-server-url=http://localhost:8080/auth
# realm名称
keycloak.realm=SpringBoot
keycloak.public-client=true
# clientID名称
keycloak.resource=product-app

We need to define some of the constraints of security, just like you use to configure Java EE application in web.xml time to be the same:

# 安全约束
keycloak.securityConstraints[0].authRoles[0]=user
keycloak.securityConstraints[0].securityCollections[0].name= common user
keycloak.securityConstraints[0].securityCollections[0].patterns[0]=/products/*

Here, we simply define each to / products / * initiated the request should be verified by the user, and the user must have a "user" in this role.

Now, we only need to configure the last property to ensure that our application will run on port 8081:

server.port=8081

The final full version of application.propertiesthe following

server.port=8081

# 是否允许HttpServletRequest属性覆盖(隐藏)控制器生成的同名模型属性。
spring.freemarker.allow-request-override=false
# 是否允许HttpSession属性覆盖(隐藏)控制器生成的同名模型属性。
spring.freemarker.allow-session-override=false
# 是否启用模板缓存。
spring.freemarker.cache=false
# 模板编码。
spring.freemarker.charset=UTF-8
# 是否检查模板位置是否存在。
spring.freemarker.check-template-location=true
# Content-Type value.
spring.freemarker.content-type=text/html
# 是否启用freemarker
spring.freemarker.enabled=true
# 设定所有request的属性在merge到模板的时候,是否要都添加到model中.
spring.freemarker.expose-request-attributes=false
# 是否在merge模板的时候,将HttpSession属性都添加到model中
spring.freemarker.expose-session-attributes=false
# 设定是否以springMacroRequestContext的形式暴露RequestContext给Spring’s macro library使用
spring.freemarker.expose-spring-macro-helpers=true
# 是否优先从文件系统加载template,以支持热加载,默认为true
spring.freemarker.prefer-file-system-access=true
# 设定模板的后缀.
spring.freemarker.suffix=.ftl
# 设定模板的加载路径,多个以逗号分隔,默认:
spring.freemarker.template-loader-path=classpath:/templates/
# 设定FreeMarker keys.
spring.freemarker.settings.template_update_delay=0
spring.freemarker.settings.default_encoding=UTF-8
spring.freemarker.settings.classic_compatible=true


# keycloak安装服务器的IP和端口
keycloak.auth-server-url=http://localhost:8080/auth
# realm名称
keycloak.realm=SpringBoot
keycloak.public-client=true
# clientID名称
keycloak.resource=product-app

# 安全约束
keycloak.securityConstraints[0].authRoles[0]=user
keycloak.securityConstraints[0].securityCollections[0].name= common user
keycloak.securityConstraints[0].securityCollections[0].patterns[0]=/products/*

So we are set up, you can put an application up and running!

To run this Spring Boot application, there are many ways to choose from. Use Maven, you can simply do it like this on the list:

mvn clean spring-boot:run

Access "products" link, you are redirected to the login page Keycloak:

Use our users "user / password" login user name and password authentication success should be redirected to the product page, otherwise it will prompt the user name and password error:

Now that you have used Keycloak added protective measures for your first Spring Boot application.

4. Reference

Spring Boot integration Keycloak Quick Start Guide

5. Code

Micro Cloud Download

Guess you like

Origin www.cnblogs.com/ifme/p/12591457.html