Spring Boot 2 OIDC(OAuth2)客户端/资源服务器未在WebClient中传播访问令牌 [英] Spring Boot 2 OIDC (OAuth2) client / resource server not propagating the access token in the WebClient

查看:1228
本文介绍了Spring Boot 2 OIDC(OAuth2)客户端/资源服务器未在WebClient中传播访问令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Github上可用的示例项目

我已经成功配置了两个Spring Boot 2 application2作为针对Keycloak的客户端/资源服务器,并且它们之间的SSO很好.

I have successfully configured two Spring Boot 2 application2 as client/resource servers against Keycloak and SSO between them is fine.

此外,我正在测试彼此之间经过身份验证的REST调用,并将访问令牌作为Authorization: Bearer ACCESS_TOKEN标头传播.

Besides, I am testing authenticated REST calls to one another, propagating the access token as an Authorization: Bearer ACCESS_TOKEN header.

启动Keycloak和应用程序后,我可以访问 http://localhost:8181/resource-server1 http://localhost:8282/resource-server-2 并在Keycloak中进行身份验证登录页面. HomeController使用WebClient调用另一个资源服务器的HelloRestController /rest/hello端点.

After starting Keycloak and the applications I access either http://localhost:8181/resource-server1 or http://localhost:8282/resource-server-2 and authenticate in the Keycloak login page. The HomeController uses a WebClient to invoke the HelloRestController /rest/hello endpoint of the other resource server.

@Controller
class HomeController(private val webClient: WebClient) {

    @GetMapping
    fun home(httpSession: HttpSession,
             @RegisteredOAuth2AuthorizedClient authorizedClient: OAuth2AuthorizedClient,
             @AuthenticationPrincipal oauth2User: OAuth2User): String {
        val authentication = SecurityContextHolder.getContext().authentication
        println(authentication)

        val pair = webClient.get().uri("http://localhost:8282/resource-server-2/rest/hello").retrieve()
                .bodyToMono(Pair::class.java)
                .block()

        return "home"
    }

}

由于请求未通过身份验证(未传播访问令牌),因此此调用返回302:

This call returns a 302 since the request is not authenticated (it's not propagating the access token):

2019-12-25 14:09:03.737 DEBUG 8322 --- [nio-8181-exec-5] o.s.s.w.a.ExceptionTranslationFilter     : Access is denied (user is anonymous); redirecting to authentication entry point

org.springframework.security.access.AccessDeniedException: Access is denied
    at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84) ~[spring-security-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233) ~[spring-security-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]

OAuth2Configuration:

OAuth2Configuration:

@Configuration
class OAuth2Config : WebSecurityConfigurerAdapter() {

    @Bean
    fun webClient(): WebClient {
        return WebClient.builder()
                .filter(ServletBearerExchangeFilterFunction())
                .build()
    }

    @Bean
    fun clientRegistrationRepository(): ClientRegistrationRepository {
        return InMemoryClientRegistrationRepository(keycloakClientRegistration())
    }

    private fun keycloakClientRegistration(): ClientRegistration {
        val clientRegistration = ClientRegistration
                .withRegistrationId("resource-server-1")
                .clientId("resource-server-1")
                .clientSecret("c00670cc-8546-4d5f-946e-2a0e998b9d7f")
                .clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
                .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
                .redirectUriTemplate("{baseUrl}/login/oauth2/code/{registrationId}")
                .scope("openid", "profile", "email", "address", "phone")
                .authorizationUri("http://localhost:8080/auth/realms/insight/protocol/openid-connect/auth")
                .tokenUri("http://localhost:8080/auth/realms/insight/protocol/openid-connect/token")
                .userInfoUri("http://localhost:8080/auth/realms/insight/protocol/openid-connect/userinfo")
                .userNameAttributeName(IdTokenClaimNames.SUB)
                .jwkSetUri("http://localhost:8080/auth/realms/insight/protocol/openid-connect/certs")
                .clientName("Keycloak")
                .providerConfigurationMetadata(mapOf("end_session_endpoint" to "http://localhost:8080/auth/realms/insight/protocol/openid-connect/logout"))
                .build()
        return clientRegistration
    }

    override fun configure(http: HttpSecurity) {
        http.authorizeRequests { authorizeRequests ->
            authorizeRequests
                    .anyRequest().authenticated()
        }.oauth2Login(withDefaults())
                .logout { logout ->
                    logout.logoutSuccessHandler(oidcLogoutSuccessHandler())
                }
    }

    private fun oidcLogoutSuccessHandler(): LogoutSuccessHandler? {
        val oidcLogoutSuccessHandler = OidcClientInitiatedLogoutSuccessHandler(clientRegistrationRepository())
        oidcLogoutSuccessHandler.setPostLogoutRedirectUri(URI.create("http://localhost:8181/resource-server-1"))
        return oidcLogoutSuccessHandler
    }
}

如您所见,我在WebClient中设置了ServletBearerExchangeFilterFunction.这是我看到的调试信息:

As you can see I'm setting a ServletBearerExchangeFilterFunction in the WebClient. This is what I've seen debugging:

SubscriberContext没有设置任何内容,因为authentication.getCredentials() instanceof AbstractOAuth2Token为false.实际上,它只是一个字符串:

The SubscriberContext isn't setting anything because authentication.getCredentials() instanceof AbstractOAuth2Token is false. Actually it is just a String:

public class OAuth2AuthenticationToken extends AbstractAuthenticationToken {

    ... 

    @Override
    public Object getCredentials() {
        // Credentials are never exposed (by the Provider) for an OAuth2 User
        return "";
    }

这是什么问题?如何自动执行令牌的传播?

What's the problem here? How can I automate the propagation of the token?

推荐答案

对于纯OAuth2/OIDC登录应用程序似乎没有现成的解决方案,我创建了

There doesn't seem to be an out of the box solution for pure OAuth2/OIDC login applications, I've created a Github issue for this.

同时,我创建了一个特定的ServletBearerExchangeFilterFunction,它从OAuth2AuthorizedClientRepository中检索访问令牌.

In the meantime, I've created a specific ServletBearerExchangeFilterFunction that retrieves the access token from the OAuth2AuthorizedClientRepository.

这是我的自定义解决方案:

This is my custom solution:

    @Autowired
    lateinit var oAuth2AuthorizedClientRepository: OAuth2AuthorizedClientRepository

    @Bean
    fun webClient(): WebClient {
        val servletBearerExchangeFilterFunction = ServletBearerExchangeFilterFunction("resource-server-1", oAuth2AuthorizedClientRepository)
        return WebClient.builder()
                .filter(servletBearerExchangeFilterFunction)
                .build()
    }

    ...

    private fun keycloakClientRegistration(): ClientRegistration {
        return ClientRegistration
                .withRegistrationId("resource-server-1")
                ...

const val SECURITY_REACTOR_CONTEXT_ATTRIBUTES_KEY = "org.springframework.security.SECURITY_CONTEXT_ATTRIBUTES"

class ServletBearerExchangeFilterFunction(private val clientRegistrationId: String,
                                          private val oAuth2AuthorizedClientRepository: OAuth2AuthorizedClientRepository?) : ExchangeFilterFunction {

    /**
     * {@inheritDoc}
     */
    override fun filter(request: ClientRequest, next: ExchangeFunction): Mono<ClientResponse> {
        return oauth2Token()
                .map { token: AbstractOAuth2Token -> bearer(request, token) }
                .defaultIfEmpty(request)
                .flatMap { request: ClientRequest -> next.exchange(request) }
    }

    private fun oauth2Token(): Mono<AbstractOAuth2Token> {
        return Mono.subscriberContext()
                .flatMap { ctx: Context -> currentAuthentication(ctx) }
                .map { authentication ->
                    val authorizedClient = oAuth2AuthorizedClientRepository?.loadAuthorizedClient<OAuth2AuthorizedClient>(clientRegistrationId, authentication, null)
                    if (authorizedClient != null) {
                        authorizedClient.accessToken
                    } else {
                        Unit
                    }
                }
                .filter { it != null }
                .cast(AbstractOAuth2Token::class.java)
    }

    private fun currentAuthentication(ctx: Context): Mono<Authentication> {
        return Mono.justOrEmpty(getAttribute(ctx, Authentication::class.java))
    }

    private fun <T> getAttribute(ctx: Context, clazz: Class<T>): T? { // NOTE: SecurityReactorContextConfiguration.SecurityReactorContextSubscriber adds this key
        if (!ctx.hasKey(SECURITY_REACTOR_CONTEXT_ATTRIBUTES_KEY)) {
            return null
        }
        val attributes: Map<Class<T>, T> = ctx[SECURITY_REACTOR_CONTEXT_ATTRIBUTES_KEY]
        return attributes[clazz]
    }

    private fun bearer(request: ClientRequest, token: AbstractOAuth2Token): ClientRequest {
        return ClientRequest.from(request)
                .headers { headers: HttpHeaders -> headers.setBearerAuth(token.tokenValue) }
                .build()
    }

}

这篇关于Spring Boot 2 OIDC(OAuth2)客户端/资源服务器未在WebClient中传播访问令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆