首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在没有登录页面的情况下将Keycloak与Spring boot(API)集成

如何在没有登录页面的情况下将Keycloak与Spring boot(API)集成
EN

Stack Overflow用户
提问于 2019-08-22 14:14:54
回答 3查看 8.5K关注 0票数 2

需要将Keycloak集成到我的spring boot应用程序中。我需要的是任何进入我的API的REST请求都会有一个头,例如"Authorisation“,它的值为"basic”,将用作身份验证令牌。对API的请求应该从keyclaok验证,而不是重定向到keycloak的任何登录页面。所有将keycloak与spring boot集成的教程都会显示登录页面或预先生成的持有者令牌。

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

代码语言:javascript
运行
复制
@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();
    }
}

我的application.properties:

代码语言:javascript
运行
复制
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文件:

代码语言:javascript
运行
复制
<?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 debug都会显示如下log:

o.k.adapters.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

密钥罩配置:

代码语言:javascript
运行
复制
Client Protocol : openid-connect
Access Type : confidential
Valid Redirect URIs: http://localhost:8081/myapi/*

上面的设置对于在JBoss EAP7上运行的一个现有应用程序的Java REST Easy框架编写的应用程序接口工作得很好。

需要帮助来理解如何配置spring boot API,以便在认证和授权请求中使用auth报头。

EN

Stack Overflow用户

发布于 2020-01-30 19:06:51

我只想给你这个类,这个类是为了通过spring boot中的

与Keycloak对话而创建的。我想这会对你有帮助的!

代码语言:javascript
运行
复制
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder
import org.keycloak.admin.client.Keycloak
import org.keycloak.admin.client.KeycloakBuilder
import org.keycloak.admin.client.resource.RealmResource
import org.keycloak.admin.client.resource.UsersResource
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Component

@Component
class KeycloakComponent {

    @Value("\${keycloakconfig.server.url}")
    var serverUrl: String = ""

    @Value("\${keycloakconfig.username}")
    var username: String = ""

    @Value("\${keycloakconfig.password}")
    var password: String = ""

    @Value("\${keycloakconfig.realm}")
    var realmName: String = ""

    @Value("\${keycloakconfig.client.id}")
    var clientId: String = ""

    @Value("\${keycloakconfig.client.secret}")
    var clientSecret: String = ""

    val keycloak: Keycloak by lazy {
        KeycloakBuilder.builder()
            .serverUrl(serverUrl)
            .username(username)
            .password(password)
            .realm(realmName)
            .clientId(clientId)
            .clientSecret(clientSecret)
            .resteasyClient(ResteasyClientBuilder().connectionPoolSize(20).register(CustomJacksonProvider()).build())
            .build()
    }

    val realm: RealmResource by lazy {
        keycloak.realm(realmName)
    }

    val userResource: UsersResource by lazy {
        realm.users()
    }


    fun keycloakForFetchUserToken(username:String, password: String): Keycloak {
        return KeycloakBuilder.builder()
            .serverUrl(serverUrl)
            .username(username)
            .password(password)
            .realm(realmName)
            .clientId(clientId)
            .clientSecret(clientSecret)
            .resteasyClient(ResteasyClientBuilder().connectionPoolSize(20).register(CustomJacksonProvider()).build())
            .build()
    }

}

如果有什么不合理的事情,请毫不犹豫地联系

票数 0
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57603010

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档