鎬庝箞浣跨敤Springboot瀹炵幇OAuth鏈嶅姟
瑕佷娇鐢⊿pring Boot瀹炵幇OAuth鏈嶅姟锛屽彲浠ユ寜鐓т互涓嬫楠よ繘琛屾搷浣滐細
- 娣诲姞Spring Security鍜孫Auth2渚濊禆锛氬湪
pom.xml
鏂囦欢涓坊鍔犱互涓嬩緷璧栵細
<dependencies>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- OAuth2 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
</dependencies>
- 閰嶇疆Spring Security鍜孫Auth2锛氬湪
application.properties
鏂囦欢涓厤缃互涓嬪睘鎬э細
# OAuth2 Client Configuration
spring.security.oauth2.client.registration.<client-id>.client-id=<client-id>
spring.security.oauth2.client.registration.<client-id>.client-secret=<client-secret>
spring.security.oauth2.client.registration.<client-id>.redirect-uri=http://localhost:8080/login/oauth2/code/<client-id>
spring.security.oauth2.client.provider.<client-id>.authorization-uri=<authorization-uri>
spring.security.oauth2.client.provider.<client-id>.token-uri=<token-uri>
spring.security.oauth2.client.provider.<client-id>.jwk-set-uri=<jwk-set-uri>
spring.security.oauth2.client.provider.<client-id>.user-info-uri=<user-info-uri>
spring.security.oauth2.client.provider.<client-id>.user-name-attribute=<user-name-attribute>
鍏朵腑锛?code><client-id>鏄疧Auth瀹㈡埛绔殑ID锛?code><client-secret>鏄疧Auth瀹㈡埛绔殑瀵嗛挜锛?code><authorization-uri>鏄巿鏉冮〉闈㈢殑URL锛?code><token-uri>鏄护鐗岀殑URL锛?code><jwk-set-uri>鏄疛WK Set鐨刄RL锛?code><user-info-uri>鏄敤鎴蜂俊鎭殑URL锛?code><user-name-attribute>鏄敤鎴峰悕绉扮殑灞炴€с€?/p>
- 鍒涘缓鎺堟潈鍥炶皟澶勭悊鍣細鍒涘缓涓€涓被瀹炵幇
AuthenticationSuccessHandler
鎺ュ彛锛屽苟瀹炵幇onAuthenticationSuccess()
鏂规硶锛岀敤浜庡鐞嗘巿鏉冩垚鍔熷悗鐨勯€昏緫銆備緥濡傦細
public class OAuth2AuthenticationSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
// 澶勭悊鎺堟潈鎴愬姛鍚庣殑閫昏緫
// ...
}
}
- 閰嶇疆鎺堟潈鍥炶皟澶勭悊鍣細鍦?code>SecurityConfig绫讳腑閰嶇疆鎺堟潈鍥炶皟澶勭悊鍣細
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private OAuth2AuthenticationSuccessHandler oauth2AuthenticationSuccessHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.oauth2Login()
.successHandler(oauth2AuthenticationSuccessHandler);
}
}
- 鍚姩搴旂敤绋嬪簭锛氫娇鐢?code>@SpringBootApplication娉ㄨВ鏍囪鍚姩绫伙紝骞舵坊鍔?code>@EnableOAuth2Client娉ㄨВ鍚敤OAuth2瀹㈡埛绔姛鑳姐€備緥濡傦細
@SpringBootApplication
@EnableOAuth2Client
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
- 娴嬭瘯鎺堟潈娴佺▼锛氬惎鍔ㄥ簲鐢ㄧ▼搴忥紝骞惰闂巿鏉冮〉闈㈣繘琛屾巿鏉冦€傛巿鏉冩垚鍔熷悗锛屽皢浼氭墽琛?code>OAuth2AuthenticationSuccessHandler绫讳腑鐨?code>onAuthenticationSuccess()鏂规硶銆?/li>
浠ヤ笂鏄娇鐢⊿pring Boot瀹炵幇OAuth鏈嶅姟鐨勫熀鏈楠わ紝鍏蜂綋鐨勫疄鐜扮粏鑺傚拰閰嶇疆鏍规嵁鍏蜂綋鐨勯渶姹傚拰OAuth鏈嶅姟鎻愪緵鍟嗙殑瑕佹眰杩涜璋冩暣銆?/p>
相关问答