Spring Security OAuth2 Client 使用 authorization_code 模式获取 AccessToken 和 RefreshToken

Spring Security OAuth2 Spring Boot About 2,255 words

说明

适用于所有OAuth2协议的IDP,本文以Keycloak为例。

添加依赖

本人以Spring Boot 3.1.5为例。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>

添加配置

默认authorization-grant-typeauthorization_code

默认redirect-uri{baseUrl}/login/oauth2/code/{registrationId}

DefaultOAuth2AuthorizationRequestResolver会解析{baseUrl}{registrationId}这两个占位符。

spring:
  security:
    oauth2:
      client:
        registration:
          keycloak:
            client-id: my-client
            client-secret: 
            scope:
              - openid
        provider:
          keycloak:
            issuer-uri: http://localhost:8080/realms/my-realm

Spring-Security配置,拦截需要被认证的URL,没有认证的请求,默认会重定向到{baseUrl}/login/oauth2/code/{registrationId}

@Bean
@Order(0)
SecurityFilterChain securityFilterChain0(HttpSecurity http) throws Exception {
    return http
            .requestMatchers(requestMatchers -> {
                requestMatchers.mvcMatchers("/web/**", "/oauth2/authorization/keycloak", "/login/oauth2/code/keycloak");
            })
            .authorizeHttpRequests(authorizeHttpRequests -> authorizeHttpRequests.anyRequest().authenticated())
            .oauth2Login(Customizer.withDefaults())
            .build();
}

获取 Token

@GetMapping("/web/home")
public String login(@RegisteredOAuth2AuthorizedClient("keycloak") OAuth2AuthorizedClient client) {
    log.info("access token: {}", client.getAccessToken().getTokenValue());
    log.info("refresh token: {}", client.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: 695 · Posted: 2024-05-09

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh