Spring Security OAuth2 Client 使用 client_credentials 模式获取 AccessToken 和 RefreshToken
Spring Security OAuth2 Spring Boot About 1,860 words说明
适用于所有OAuth2
协议的IDP
,本文以Keycloak
为例。
添加依赖
本人以Spring Boot 3.1.5
为例。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
添加配置
spring:
security:
oauth2:
client:
registration:
keycloak:
client-id: my-client
client-secret:
authorization-grant-type: client_credentials
scope:
- openid
provider:
keycloak:
issuer-uri: http://localhost:8080/realms/my-realm
获取 Token
@Autowired
private ClientRegistrationRepository clientRegistrationRepository;
ClientRegistration keycloak = clientRegistrationRepository.findByRegistrationId("keycloak");
DefaultClientCredentialsTokenResponseClient client = new DefaultClientCredentialsTokenResponseClient();
OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(keycloak);
OAuth2AccessTokenResponse tokenResponse = client.getTokenResponse(request);
String accessToken = tokenResponse.getAccessToken().getTokenValue();
String refreshToken = tokenResponse.getRefreshToken().getTokenValue();
刷新 Token
@Autowired
private ClientRegistrationRepository clientRegistrationRepository;
String refreshToken = "xxx";
DefaultRefreshTokenTokenResponseClient client = new DefaultRefreshTokenTokenResponseClient();
ClientRegistration keycloak = clientRegistrationRepository.findByRegistrationId("keycloak");
OAuth2AccessToken oAuth2AccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "1", null, null);
OAuth2RefreshToken oAuth2RefreshToken = new OAuth2RefreshToken(refreshToken, null);
OAuth2RefreshTokenGrantRequest request = new OAuth2RefreshTokenGrantRequest(keycloak, oAuth2AccessToken, oAuth2RefreshToken);
OAuth2AccessTokenResponse tokenResponse = client.getTokenResponse(request);
Views: 727 · Posted: 2024-05-08
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...