2

In my previous implementation I was using OAuth2FeignRequestInterceptor. But from Spring security 5 onwards, OAuth2FeignRequestInterceptor seems to be deprecated. What is the alternative to achieve the same ?. I searched lot of blogs and threads, but couldn't find any answer.

4

1 回答 1

3

build.gradle.kts

implementation("org.springframework.security:spring-security-oauth2-client")

application.yml

spring:
  security:
    oauth2:
      client:
        registration:
          keycloak: // <- replace with your custom oauth2 client details
            provider: keycloak
            client-id: [keycloak-client-id]
            client-secret: [keycloak-client-secret]
            authorization-grant-type: client_credentials
            scope: openid
        provider:
          keycloak: // <- replace with your custom oauth2 provider details
            authorization-uri: http://localhost:8080/auth/realms/yourealm/protocol/openid-connect/auth
            token-uri: http://localhost:8080/auth/realms/yourealm/protocol/openid-connect/token

Oauth2Config

@Configuration
class Oauth2Config {
  @Bean
  fun authorizedClientManager(
    clientRegistrationRepository: ClientRegistrationRepository?,
    authorizedClientRepository: OAuth2AuthorizedClientRepository?
  ): OAuth2AuthorizedClientManager? {
    val authorizedClientProvider: OAuth2AuthorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
      .authorizationCode()
      .clientCredentials()
      .build()
    val authorizedClientManager = DefaultOAuth2AuthorizedClientManager(clientRegistrationRepository, authorizedClientRepository)
    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider)

    return authorizedClientManager
  }
}

FeignOauth2Configuration

class FeignOauth2Configuration (private val authorizedClientManager: OAuth2AuthorizedClientManager) {
  @Bean
  fun oauth2HttpRequestInterceptor(): RequestInterceptor {
    return RequestInterceptor { request ->
      request.headers()["Authorization"] = listOf("Bearer ${getAccessToken()?.tokenValue}")
    }
  }

  private fun getAccessToken(): OAuth2AccessToken? {
    val request = OAuth2AuthorizeRequest
      .withClientRegistrationId("keycloak")
      .principal("client-id")
      .build()
    return authorizedClientManager.authorize(request)?.accessToken
  }
}

UserClient

@FeignClient(name="user-service", configuration = [FeignOauth2Configuration::class])
interface UserClient {
  @GetMapping("/users")
  fun getAllUsers(): List<UserDto>
}
于 2021-03-08T19:11:19.007 回答