Spring Security OAuth2 Client 使用 password 模式获取 AccessToken 和 RefreshToken
Spring Security OAuth2 Keycloak About 1,807 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: password
scope:
- openid
provider:
keycloak:
issuer-uri: http://localhost:8080/realms/my-realm
获取 Token
@Autowired
private ClientRegistrationRepository clientRegistrationRepository;
ClientRegistration keycloak = clientRegistrationRepository.findByRegistrationId("keycloak");
DefaultPasswordTokenResponseClient client = new DefaultPasswordTokenResponseClient();
OAuth2PasswordGrantRequest request = new OAuth2PasswordGrantRequest(keycloak, "my-user", "my-user");
OAuth2AccessTokenResponse tokenResponse = client.getTokenResponse(request);
String accessToken = tokenResponse.getAccessToken().getTokenValue();
String refreshToken = tokenResponse.getRefreshToken().getTokenValue();
刷新 Token
@Autowired
private ClientRegistrationRepository clientRegistrationRepository;
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: 400 · Posted: 2024-05-07
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...