从Spring Boot应用程序连接到Keycloak

首先

在这里,我们将尝试安装和配置Keycloak,并从Spring Boot应用程序进行连接。这只是一份备忘录,所以说明只提供最基本的内容(可能会在有空的时候添加说明)。

环境

以下是我使用的环境和版本。

    • CentOS 7.5(Keycloak)

 

    • Keycloak 10.0.2

 

    Spring Boot 2.3.1

将Spring Boot应用程序在本地的Windows上进行开发和执行。

安装Keycloak

在安装Keycloak之前,首先需要安装OpenJDK(1.8)。

# yum install java

关于Keycloak的安装,只需从下面的URL下载并解压模块(zip文件),然后部署到服务器即可。

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

这次下载的是”keycloak-10.0.2.zip”。

# unzip keycloak-10.0.2.zip 

Keycloak的启动和配置

在启动Keycloak之前,请创建管理员账户(admin)。

# cd keycloak-10.0.2
# ./bin/add-user-keycloak.sh -u admin
Press ctrl-d (Unix) or ctrl-z (Windows) to exit
Password: 
Added 'admin' to '/opt/keycloak-10.0.2/standalone/configuration/keycloak-add-user.json', restart server to load user

接下来启动Keycloak。为了能够从本地以外的地方进行访问,我们使用了“-b 0.0.0.0”来启动。

# ./bin/standalone.sh -b 0.0.0.0
~省略~
00:35:51,363 INFO  [org.jboss.as] (Controller Boot Thread) WFLYSRV0060: Http management interface listening on http://127.0.0.1:9990/management
00:35:51,363 INFO  [org.jboss.as] (Controller Boot Thread) WFLYSRV0051: Admin console listening on http://127.0.0.1:9990
00:35:51,363 INFO  [org.jboss.as] (Controller Boot Thread) WFLYSRV0025: Keycloak 10.0.2 (WildFly Core 11.1.1.Final) started in 22714ms - Started 591 of 889 services (606 services are lazy, passive or on-demand)

在启动后,使用浏览器打开以下网址。

    http://[ホスト名]:8080/auth/

在浏览器中,将会打开以下页面。

image.png

点击[管理控制台]将跳转至登录界面。

image.png

使用已创建的管理员帐户(admin)进行登录。

image.png

登录后,首先创建一个领域(realm)。
这里将其命名为”测试领域”。

image.png

选择[Clients]选项卡,点击[Create]来创建外部应用程序的客户端。

image.png

输入客户端ID。在这里我们将其设为”login-app”。

image.png

完成后,在列表中选择已创建的客户端,并将“Valid Redirect URIs”更改为“http://localhost:8081/*”。这将成为我们即将创建的Spring Boot应用程序的URI。

image.png

制作卷筒

将鼠标指向[角色]选项卡,然后点击[添加角色],以创建下一个角色。

image.png

输入角色名(用户),然后点击[保存]按钮。

image.png

创建用户

选择[用户]标签,并点击[添加用户]来创建用户。

image.png

输入用户名[user1],然后点击[保存]。

image.png

请点击[凭据]选项卡,并输入密码。

image.png
image.png

角色与用户的关联

选择[角色映射]选项卡,以将创建的用户(user1)与角色(user)关联起来,并将user1从[可用角色]移动到[已分配角色]。

image.png

使用Spring Boot和Keycloak

使用Keycloak客户端适配器与Spring Boot连接。

pom.xml => 项目对象模型 (POM) 文件

创建一个具有以下 pom.xml 的 Maven 项目。

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>test</groupId>
    <artifactId>spring-boot-keycloak</artifactId>
    <version>0.0.1</version>
    <packaging>jar</packaging>

    <properties>
        <keycloak-adapter-bom.version>10.0.2</keycloak-adapter-bom.version>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.1.RELEASE</version>
    </parent>

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
            <version>2.5.1</version>
            <scope>runtime</scope>
        </dependency>

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

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

</project>

主要应用程序

这是本次重点介绍的应用程序类。
这是一个普通的Spring Boot应用程序。

@SpringBootApplication
public class App {

    public static void main(String... args) {
        SpringApplication.run(App.class, args);
    }

}

创建控制器和HTML文件。

将Controller(控制器)类按以下方式创建。
“/” -> index.html,”hello” -> hello.html进行加载。

@Controller
public class WebController {

    @GetMapping(path = "/")
    public String index() {
        return "index";
    }

    @GetMapping(path = "/hello")
    public String customers(Principal principal, Model model) {

        model.addAttribute("username", principal.getName());
        return "hello";
    }

}

index.html和hello.html使用Java模板引擎Thymeleaf。
当访问index.html时会显示登录链接,点击链接后经由KeyCloak登录,然后转至hello.html页面。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body>
    <div class="container">
        <div>
            <h1>Portal</h1>
        </div>
        <div>
            <a th:href="@{/hello}">Login</a>
        </div>
    </div>
</body>
</html>

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body>
    <div id="container">
        <h1>
            Hello, <span th:text="${username}"></span>
        </h1>
    </div>
</body>
</html>

Keycloak和应用程序的配置

应用程序的属性设置如下所示。

# server port
server.port=8081

# Keycloak
keycloak.auth-server-url=http://[Keycloakサーバのホスト名]:8080/auth
# レルム名を設定する。
keycloak.realm=test realm
# クライアントIDを設定する。
keycloak.resource=login-app
keycloak.public-client=true
## OpenID ConnectのIDトークン属性を設定。
keycloak.principal-attribute=preferred_username

Keycloak客户端适配器

使用Keycloak客户端适配器(keycloak-spring-security-adapter)进行访问控制的配置。

@KeycloakConfiguration
class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        KeycloakAuthenticationProvider provider = keycloakAuthenticationProvider();
        provider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
        auth.authenticationProvider(provider);
    }

    // Spring Security AdapterとSpring Boot Adapterを一緒に使用する場合、application.propertiesから
    // 設定情報を取得するために必要。
    @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("/hello*")
            .hasRole("user")
            .anyRequest().permitAll();
    }
}

重点在以下几个方面,当匹配到”/hello*”时,仅在拥有”user”角色的情况下进行授权。


        http.authorizeRequests()
            .antMatchers("/hello*")
            .hasRole("user")
            .anyRequest().permitAll();

程序编写已经完成。

启动已创建的Spring Boot应用程序

为了启动已创建的Spring Boot应用程序,请执行以下命令。

mvn clean spring-boot:run

在启动后,通过以下URL访问Spring Boot应用程序。

    http://localhost:8081/

当您访问时,会显示一个具有以下登录链接的屏幕。

image.png

当您点击此链接时,将会匹配”/hello”,并转到Keycloak进行身份验证。在登录页面上,请使用具有”用户1″和”用户”角色的Keycloak管理控制台创建的用户进行登录。

image.png

如果是初次登录,将显示如下更改密码的选项。

image.png

成功登陆后,会跳转到仅显示用户名的页面。

image.png

请提供更多的上下文,以便我可以准确地为您进行翻译。

    A Quick Guide to Using Keycloak with Spring Boot
bannerAds