首页 > 解决方案 > 如何在没有登录页面的情况下将 Keycloak 与 Spring Boot(API) 集成

问题描述

需要将 Keycloak 与我的 Spring Boot 应用程序集成。我需要的是任何到达我的 API 的 REST 请求都会有一个标头,例如“授权”,它的值将是“基本”,用作身份验证令牌。到 API 的请求应该从 keyclaok 进行验证,而不需要重定向到任何 keycloak 的登录页面。所有将 keycloak 与 spring boot 集成的教程都显示了登录页面或预生成的不记名令牌。

当我尝试这样做时,下面是我的 SecurityConfig.java:

@Configuration
@EnableWebSecurity
@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {

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

    @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("/myapi*").hasRole("user").anyRequest().permitAll();
    }
}

我的应用程序属性:

server.port=8081
keycloak.auth-server-url=http://localhost:9080/auth
keycloak.realm=myrealm
keycloak.resource=myclient
keycloak.public-client=false
keycloak.credentials.secret=mysecret
keycloak.use-resource-role-mappings=true
keycloak.enabled=true
keycloak.ssl-required=external

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 http://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.1.7.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.example.api</groupId>
<artifactId>springboot-kc-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-kc-api</name>

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

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

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</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-devtools</artifactId>
        <scope>runtime</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</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>

</dependencies>

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

每当发出 GET 请求时,keycloak 调试都会显示以下日志:

okadapters.OAuthRequestAuthenticator:发送重定向到登录页面:http://localhost:9080/auth/realms/myrealm/protocol/openid-connect/auth?response_type=code&client_id=myclient&redirect_uri=http%3A%2F%2Flocalhost%3A8081%2Fmyapi% 2Fsampleget?param1=val1&state=a2b5072a-acb8-4bf6-8f33-b3f25deab492&login=true&scope=openid

密钥斗篷配置:

Client Protocol : openid-connect
Access Type : confidential
Valid Redirect URIs: http://localhost:8081/myapi/*

对于在 JBoss EAP 7 上运行的现有应用程序之一,用 Java REST Easy 框架编写的 API 可以正常工作。

需要帮助了解如何配置 Spring Boot API 以在请求中使用 auth 标头来对请求进行身份验证和授权。

标签: restspring-bootkeycloak

解决方案


这可以通过启用该bearer only模式来实现。首先通过以下方式在您的 Spring Boot 服务中启用此功能application.properties

keycloak.bearer-only=true

有关这方面的更多详细信息,请参见 [1]。

您也可以在管理控制台中为您的客户强制执行此操作。


推荐阅读