美文网首页
SpringBoot 2.2.5与KeyCloak9.0.0集成

SpringBoot 2.2.5与KeyCloak9.0.0集成

作者: dgatiger | 来源:发表于2020-03-18 00:33 被阅读0次

1.测试目标

  • Spring Boot写的Restful API前后端分离的情况下与KeyCloak集成
  • 普通的Spring 项目,前后端未分离的情况与KeyCloak集成

2.建立测试用KeyCloak配置

可以登录KeyCloak管理后台(安装配置可参考https://www.jianshu.com/p/de1e415ddc27)。本次测试用脚本进行,假设初始化系统的超管账户密码均为root。kcadm.sh脚本位于KeyCloak目录的./bin目录下。

  • 登录root账户,后续脚本不用登录
./kcadm.sh config credentials --server http://localhost:8080/auth --realm master --user root --password root
  • 创建realm
realmName='springboot-integration'
#删除存在的realm,这样下面的client/user/roles都会删除
./kcadm.sh delete realms/$realmName -r $realmName

#创建
realmId=$(./kcadm.sh create realms -s realm=$realmName -s enabled=true  2>&1 | awk -F "'" '{print $2}')
  • 创建springboot-security client,用于API访问更换token以及sso登录验证。
#创建换token的公开认证用client
openClientName='springboot-security'
#为了调试方便,直接指定secret code
openSecret='d0b8122f-8dfb-46b7-b68a-f5cc4e25d000'
openClient=$(./kcadm.sh create clients -r $realmId -s clientId=$openClientName -s enabled=true -s publicClient=true -s  'redirectUris=["http://localhost:9090/*","http://127.0.0.1:9090/*"]' -s baseUrl=http://localhost:9090 -s adminUrl=http://localhost:9090 -s clientAuthenticatorType=client-secret -s secret=$openSecret -s directAccessGrantsEnabled=true 2>&1 | awk -F "'" '{print $2}')
  • 创建springboot-rest-api client,保护的API用
#创建受保护的client
restClientName='springboot-rest-api'
#为了调试方便,直接指定secret code
restSecret='6e32611b-8e10-4afe-ac0b-0f64c4022390'
restClient=$(./kcadm.sh create clients -r $realmId -s clientId=$restClientName -s enabled=true  -s baseUrl=http://localhost:9091 -s bearerOnly=true -s secret=$restSecret  2>&1 | awk -F "'" '{print $2}')
  • 查看受保护的client配置,参照配置springboot的application.yml文件
#查看受保护的client配置
echo "35.restClient: "$restClient" 的配置情况: "
./kcadm.sh get clients/$restClient/installation/providers/keycloak-oidc-keycloak-json -r $realmId
  • 创建roles,位于realm,也可以创建位于client的roles
#给realm创建roles
echo "17.给"$realmId"创建两个角色 "
./kcadm.sh create roles -r $realmId -s name=user -s "description=$realmId user role"
./kcadm.sh create roles -r $realmId -s name=admin -s "description=$realmId admin role"

#显示realm的roles清单
echo "25.realm: "$realmId" 的roles: "
./kcadm.sh get roles -r $realmId
  • 创建账户,一个admin,加入admin role;一个user加入user role.
#创建管理员账号,归realm
adminId=$(./kcadm.sh create users -r $realmId -s username=admin -s firstName=wu -s lastName=Wang -s email=admin@mail.xx.com  -s enabled=true   2>&1 | awk -F "'" '{print $2}')
#设置密码
./kcadm.sh update users/$adminId/reset-password -r $realmId -s type=password -s value=123456 -s temporary=false -n
#设置为realm的角色
./kcadm.sh add-roles --uusername admin --rolename admin -r $realmId

#创建普通用户账号,归realm
userId=$(./kcadm.sh create users -r $realmId -s username=user -s firstName=san -s lastName=Zhang -s email=user@mail.xx.com -s enabled=true  2>&1 | awk -F "'" '{print $2}')
#设置密码
./kcadm.sh update users/$userId/reset-password -r $realmId -s type=password -s value=123456 -s temporary=false -n
#设置为realm的角色
./kcadm.sh add-roles --uusername user --rolename user -r $realmId
  • 获得访问token测试
#获得访问token
export adminToken=$(curl -ss --data "grant_type=password&client_id=$openClientName&client_secret=$openSecret&username=admin&password=123456" http://localhost:8080/auth/realms/$realmId/protocol/openid-connect/token | jq -r .access_token)
export userToken=$(curl -ss --data "grant_type=password&client_id=$openClientName&client_secret=$openSecret&username=user&password=123456" http://localhost:8080/auth/realms/$realmId/protocol/openid-connect/token | jq -r .access_token)
  • 测试API.(API应用开发完成并启动后)
echo "\n\nAPI访问测试: "
echo "\n『adminToken+admin』 result : "
curl -H "Authorization: bearer $adminToken" http://localhost:9091/admin
echo "\n\n『adminToken+user』 result : "
curl -H "Authorization: bearer $adminToken" http://localhost:9091/user
echo "\n\n『userToken+admin』 result : "
curl -H "Authorization: bearer $userToken" http://localhost:9091/admin
echo "\n\n『userToken+user』 result : "
curl -H "Authorization: bearer $userToken" http://localhost:9091/user

3.编码--父项目

管理spingboot及keycloak版本,非必须

  • 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.5.RELEASE</version>
    </parent>

    <groupId>com.dimaidt.springboot-keycloak</groupId>
    <artifactId>springboot-keycloak</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-keycloak</name>
    <description>Demo project for Spring Boot</description>
    <packaging>pom</packaging>


    <modules>
        <module>api-demo</module>
        <module>web-demo</module>
    </modules>

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

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.keycloak</groupId>
                <artifactId>keycloak-spring-boot-starter</artifactId>
                <version>${keycloak.version}</version>
            </dependency>
            <dependency>
                <groupId>org.keycloak</groupId>
                <artifactId>keycloak-spring-security-adapter</artifactId>
                <version>${keycloak.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

</project>

4.编码--子项目1:api-demo

  • 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>com.dimaidt.springboot-keycloak</groupId>
        <artifactId>springboot-keycloak</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

    <groupId>com.dimaidt.springboot-keycloak</groupId>
    <artifactId>api-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>api-demo</name>
    <description>Demo project for Spring Boot</description>

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

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-spring-boot-starter</artifactId>
        </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>
  • application.yml文件内容
server:
  port: 9091

keycloak:
  realm: springboot-integration
  resource: springboot-rest-api
  bearer-only: true
  credentials:
      secret: 6e32611b-8e10-4afe-ac0b-0f64c4022390
  auth-server-url: http://localhost:8080/auth
  ssl-required: external
  confidential-port: 0


logging:
    level:
        org:
            springframework:
                security:  DEBUG

  • src目录结构
src
├── main
│   ├── java
│   │   └── com
│   │       └── dimaidt
│   │           └── springbootkeycloak
│   │               └── apidemo
│   │                   ├── ApiDemoApplication.java
│   │                   ├── config
│   │                   │   ├── KeycloakConfig.java
│   │                   │   └── KeycloakSecurityConfig.java
│   │                   └── controller
│   │                       └── APIController.java
│   └── resources
│       └── application.yml
└── test
    └── java
        └── com
            └── dimaidt
                └── springbootkeycloak
                    └── apidemo
                        └── ApiDemoApplicationTests.java

5.编码--子项目2:web-demo

  • 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>com.dimaidt.springboot-keycloak</groupId>
        <artifactId>springboot-keycloak</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

    <groupId>com.dimaidt.springboot-keycloak</groupId>
    <artifactId>web-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>web-demo</name>
    <description>Demo project for Spring Boot</description>

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

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </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>
  • application.yml文件内容
server:
  port: 9090

keycloak:
  realm: springboot-integration
  resource: springboot-security
  auth-server-url: http://localhost:8080/auth
  ssl-required: external
  confidential-port: 0
  public-client: true
  principal-attribute: preferred_username


logging:
  level:
    org:
      springframework:
        security:  DEBUG

  • src目录结构
src
├── main
│   ├── java
│   │   └── com
│   │       └── dimaidt
│   │           └── springbootkeycloak
│   │               └── webdemo
│   │                   ├── WebDemoApplication.java
│   │                   ├── config
│   │                   │   ├── KeycloakConfig.java
│   │                   │   └── SecurityConfig.java
│   │                   ├── controller
│   │                   │   └── LibraryController.java
│   │                   ├── model
│   │                   │   └── Book.java
│   │                   └── repository
│   │                       └── BookRepository.java
│   └── resources
│       ├── application.yml
│       ├── static
│       │   ├── css
│       │   │   └── style.css
│       │   └── images
│       │       └── public-library-bookshelves-books.jpg
│       └── templates
│           ├── books.html
│           ├── index.html
│           └── manager.html
└── test
    └── java
        └── com
            └── dimaidt
                └── springbootkeycloak
                    └── webdemo
                        └── WebDemoApplicationTests.java

详细说明请参考参考链接,本次测试的脚本及代码均有参考其内容,在此同时向原作者致敬。

6.附件

  • 源代码
https://gitee.com/dgatiger/springboot-keycloak
https://github.com/dgatiger/springboot-keycloak
  • 参考
https://my.oschina.net/shicheng2014/blog/3011456
https://www.lanhusoft.com/Article/740.html
https://www.lanhusoft.com/article/741.html

相关文章

网友评论

      本文标题:SpringBoot 2.2.5与KeyCloak9.0.0集成

      本文链接:https://www.haomeiwen.com/subject/fzyfyhtx.html