使用 Spring Security 6 配置 Keycloak 21

Pet*_*zov 5 java spring spring-security spring-boot

我正在尝试设置 Spring Security 以与 Keycloak 21 一起使用,但不幸的是 Internet 上的大多数教程都已过时。我将客户端和领域配置到 Keycloak 中,但 Spring 安全性不清楚应该是什么。我尝试了此链接中的代码:

我添加了这些 gradle 依赖项:

implementation 'org.springframework.boot:spring-boot-starter-oauth2-client:3.1.0'
implementation 'org.springframework.boot:spring-boot-starter-security:3.1.0'
implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server:3.1.0'
Run Code Online (Sandbox Code Playgroud)

和这个 yml 配置:

spring:
  security:
    oauth2:
      client:
        provider:
          keycloak:
            issuer-uri: https://ip/realms/admin_console_realm
        registration:
          keycloak-login:
            authorization-grant-type: authorization_code
            client-name: My Keycloak instance
            client-id: admin_console_client
            client-secret: qwerty
            provider: keycloak
            scope: openid,profile,email,offline_access
      resourceserver:
        jwt:
          issuer-uri: https://ip/realms/admin_console_realm
          jwk-set-uri: https://ip/realms/admin_console_realm/protocol/openid-connect/certs
Run Code Online (Sandbox Code Playgroud)

目前尚不清楚我需要在此处添加什么作为 Spring 安全配置:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {

        httpSecurity.authorizeHttpRequests()
                .requestMatchers("/*").hasAuthority("ROLE_TECH_SUPPORT")
                .anyRequest().authenticated()
                .and()
                .oauth2Login();

        return  httpSecurity.build();
    }
}
Run Code Online (Sandbox Code Playgroud)

我将角色添加到Keycloak客户端中:

在此输入图像描述

当我在浏览器中打开 Rest API 链接时,我会被重定向到 Keycloak 的登录页面。身份验证成功后我得到:

Access to ip was deniedYou don't have authorization to view this page.
HTTP ERROR 403
Run Code Online (Sandbox Code Playgroud)

你知道我该如何解决这个问题吗?

Rit*_*rma 5

如果您尝试公开使用 Keycloak 服务器(身份验证服务器)保护的其余 API,那么您的应用程序是 OAuth2 资源服务器而不是 OAuth2 客户端服务器,并且您也不能使用浏览器来访问您的其余 API,除非它们是公共的。对于具有 REST API 的资源服务器,您可以使用以下代码

  1. 应用程序.yml
spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: http://<KEYCLOAK_SERVER_IP>/realms/<YOUR_REALM_NAME>
          jwk-set-uri: http://<KEYCLOAK_SERVER_IP>/realms/<YOUR_REALM_NAME>/protocol/openid-connect/certs
Run Code Online (Sandbox Code Playgroud)
  1. 从Keycloak服务器获取JWT TOKEN(这个curl相当于postman请求keycloak来获取访问令牌,你可以在这里找到更多信息https://documenter.getpostman.com/view/7294517/SzmfZHnd
curl --location 'http://<KEYCLOAK_SERVER_IP>/realms/test/protocol/openid-connect/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'username=<YOUR_USER_NAME>' \
--data-urlencode 'password=<YOUR_USER_PASSWORD>' \
--data-urlencode 'grant_type=password' \
--data-urlencode 'client_id=<KEYCLOAK_CLIENT_ID>' \
--data-urlencode 'client_secret=<KEYCLOAK_CLIENT_SECRET>' \
--data-urlencode 'scope=openid'
Run Code Online (Sandbox Code Playgroud)
  1. 使用https://jwt.io/检查您的访问令牌
...
"realm_access": {
    "roles": [
      "default-roles-test",
      "offline_access",
      "MY_REALM_ROLE",
      "uma_authorization"
    ]
  },
  "resource_access": {
    "test-client": {
      "roles": [
        "MY_CLIENT_ROLE"
      ]
    },
...
Run Code Online (Sandbox Code Playgroud)

现在,我们需要告诉 spring security 从哪里查找 JWT 令牌中的角色信息。

  1. WebSecurityConfig.java
spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: http://<KEYCLOAK_SERVER_IP>/realms/<YOUR_REALM_NAME>
          jwk-set-uri: http://<KEYCLOAK_SERVER_IP>/realms/<YOUR_REALM_NAME>/protocol/openid-connect/certs
Run Code Online (Sandbox Code Playgroud)

确保您在 Keycloak 中具有正确的用户角色映射。

现在,为了使用您的 REST API,您可以使用 Postman。在 Postman 中添加 Bearer Token Authorization 并使用 keycloak 服务器最新生成的访问令牌。