spring oauth2 接入 keycloak

依賴包

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

啟動類

啟動類

@SpringBootApplication
@EnableWebSecurity
public class KeycloakDemoApplication extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
                .authorizeRequests(a -> a
                        .antMatchers("/", "/error", "/webjars/**").permitAll()
                        .anyRequest().authenticated()
                )
                .exceptionHandling(e -> e
                        .authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
                )
                .logout(l -> l
                        .logoutSuccessUrl("/").permitAll()
                )
                .csrf(c -> c
                        .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                )
                .oauth2Login();
        // @formatter:on
    }

    public static void main(String[] args) {
        SpringApplication.run(KeycloakDemoApplication.class, args);
    }

}

resources/static/index.html

<div class="container unauthenticated">
    With GitHub: <a href="/oauth2/authorization/keycloak">click here</a>
</div>

spring 配置

核心路徑

  • 執(zhí)行首次跳轉(zhuǎn)地址模板: /oauth2/authorization/{registrationId}
  • redirectUri: 默認的模板 {baseUrl}/login/oauth2/code/{registrationId}

配置樣本

spring:
  security:
    oauth2:
      client:
        registration:
          keycloak:
            clientId: test
            clientSecret: zwd2yOiUqn0jowH2hrPYJvFsCGWnVZvL
            authorizationGrantType: authorization_code
            redirectUri: http://localhost:8082/login/oauth2/code/keycloak
        provider:
          keycloak:
            authorizationUri: http://localhost:8080/realms/test/protocol/openid-connect/auth
            tokenUri: http://localhost:8080/realms/test/protocol/openid-connect/token
            userInfoUri: http://localhost:8080/realms/test/protocol/openid-connect/userinfo
            userNameAttribute: preferred_username

代碼跟蹤

  • DefaultOAuth2AuthorizationRequestResolver: 用于讀取當前 provider 配置, 并執(zhí)行跳轉(zhuǎn)邏輯
  • OAuth2LoginAuthenticationFilter: 用于處理callback 的地址, 執(zhí)行 code 換 open id token 的操作
  • OAuth2AuthorizationCodeAuthenticationProvider: 用于code 交換 access token, refresh token
  • DefaultOAuth2UserService: 用于用戶信息加載
  • AuthorizationGrantType: 定義授權(quán)類型

遇到的問題

  1. 配置 userNameAttribute: preferred_username 遺漏, 會導(dǎo)致Missing required "user name" attribute name in UserInfoEndpoint for Client Registration

文檔

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容