springboot整合keycloak


1. Keycloak是什么?

Keycloak是一種面向現代應用程序和服務的開源的IAM(身份識別與訪問管理)解決方案。

Keycloak提供了單點登錄(SSO)、Identity Brokering和社交賬號登錄、User Federation、客戶端適配器、管理控制台和帳戶管理控制台等特性。想了解更多關於Keycloak的信息,請訪問官方頁面

在本教程中,我們將使用Keycloak的管理控制台進行配置,然后在Spring Boot應用程序中使用Keycloak Client Adapter和Keycloak服務器連接起來。

2. 安裝配置一個Keycloak服務器

1. 安裝部分參考 keycloak9.0.2單機模式整合mysql8

2. 創建一個 Realm

讓我們將鼠標導航到左上角,找到“Add Realm”按鈕:

我們把它命名為“SpringBoot“:

3 .創建一個客戶端

我們需要在應用程序中添加一個客戶端,所以我們點擊“Create”。我們配置新的Client ID為“product-app“:

在下一個頁面中,對於本教程而言,除了“Valid Redirect URIs 字段”之外,我們將保留所有缺省值。配置完成后,將被重定向到端口8081

點擊保存

4. 創建一個角色和用戶

Keycloak使用Role-Based Access。因此,每個用戶都必須有一個角色。
我們需要導航到“Role”頁面:

然后,我們添加 “user”角色:

現在我們已經有了一個可以分配給用戶的角色,但是還沒有一個用戶。因此,讓我們去“Users”頁面新增一個:

我們創建用戶“user1”:

一旦用戶被創建,用戶信息將展示在這里:

進入“Credentials”選項卡,並將把密碼設置為“123456”,注意關閉Temporary ,點擊重置密碼:

導航到“Role Mappings”選項卡,並分配用戶角色:

3. 創建一個Spring Boot應用程序

為了能夠保護Spring Boot應用程序,您必須將Keycloak Spring Boot適配器JAR添加到您的應用程序。然后,您必須通過正常的Spring Boot配置(application.properties)提供一些額外的配置。讓我們看一下這些步驟。

1. 官方文檔參考

Keycloak Spring Boot適配器利用了Spring Boot的自動配置功能,因此您所要做的就是將Keycloak Spring Boot啟動器添加到您的項目中。

要使用Maven添加它,請將以下內容添加到您的依賴項中:

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

添加適配器BOM依賴項:

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

上面是官方的參考資料

創建一個springboot簡單項目包含如下jar包

  • Web
  • Freemarker
  • Keycloak

2. 創建springboot項目

最終的pom.xml文件如下

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

我們的應用程序會比較簡單,只包含兩個頁面:

  • 一個 index.html,它將是登錄頁面,里面只包含產品頁面的鏈接。
  • product.ftl,它將是我們的產品頁面的模板,只能被通過了身份驗證的用戶訪問到。

首先我們在“/src/resources/static”目錄中創建一個簡單的index.html文件:

<html>

 <head>
   <title>My awesome landing page</title>
 </head>

 <body>
   <h1>Landing page</h1> <a href="/products">My products</a>
 </body>

</html>

現在,我們需要一個控制器:

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 "/";
    }
}

你會發現這很簡單,就是定義了產品頁面的映射,然后再為注銷操作定義一個映射。你還會注意到,我們調用了一個“ProductService”,它會返回一個字符串列表,我們把這個列表放到 Spring MVC Model 對象里面去,所以我們要創建這個服務:

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");
    }
}

我們還需要創建 product.ftl 模板。要在“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>

在這里,我們簡單地遍歷了 Spring MVC Model 對象中的產品列表,並添加一個從我們的應用程序中注銷的鏈接。

3. springboot中配置keycloak

我們要做的就是向 application.properties 中添加一些keycloak相關的屬性。

一些屬性是必須要有的:

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

我們需要定義一些安全方面的約束,就像你在 web.xml 中使用 Java EE 應用的時候要進行的配置一樣:

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

在這里,我們簡單地定義每個向 /products/* 發起的請求都應該通過用戶驗證,而且該用戶得有“user”這個角色。

現在,我們只需要配置最后一個屬性來確保我們的應用程序將會在端口8081上運行:

server.port=8081

最終完整版的application.properties如下

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/*

這樣我們就都設置好了,可以把應用程序運行起來了!

要運行這個 Spring Boot 應用程序,有很多方式可以選擇。使用 Maven 的話,你可以簡單地像下面這樣做就行了:

mvn clean spring-boot:run

訪問“products”鏈接,會被重定向到 Keycloak 登錄頁面:

使用我們的用戶“user/password”進行登錄,用戶名和密碼驗證成功應該會重定向到產品頁面,否則會提示用戶名密碼錯誤:

現在你已經使用 Keycloak 為你的第一個 Spring Boot 應用程序加上了防護措施。

4. 參考

Spring Boot整合Keycloak快速入門指南

5. 代碼

微雲下載


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM