本文介绍了OAuth2FeignRequestInterceptor 的替代方案,因为它现在已被弃用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我之前的实现中,我使用的是 OAuth2FeignRequestInterceptor.但是从 Spring security 5 开始,OAuth2FeignRequestInterceptor 似乎已被弃用.实现相同目标的替代方法是什么?我搜索了很多博客和主题,但找不到任何答案.
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.
推荐答案
build.gradle.kts
build.gradle.kts
implementation("org.springframework.security:spring-security-oauth2-client")
应用程序.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
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
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
}
}
用户客户端
@FeignClient(name="user-service", configuration = [FeignOauth2Configuration::class])
interface UserClient {
@GetMapping("/users")
fun getAllUsers(): List<UserDto>
}
这篇关于OAuth2FeignRequestInterceptor 的替代方案,因为它现在已被弃用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!