Spring Boot 与 Spring Security 的集成及 OAuth2 实现
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final ClientRegistrationRepository clientRegistrationRepository;
public SecurityConfig(ClientRegistrationRepository clientRegistrationRepository) {
this.clientRegistrationRepository = clientRegistrationRepository;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// 其他配置 ...
.oauth2Login()
.loginPage("/login") // 自定义登录页面路径
.authorizationEndpoint()
.baseUri("/oauth2/authorize") // 授权端点基础URI
.and()
.redirectionEndpoint()
.baseUri("/oauth2/callback") // 回调端点基础URI
.and()
.tokenEndpoint()
.baseUri("/oauth2/token") // 令牌端点基础URI
.and()
.and()
// 其他配置 ...
;
}
}
这段代码演示了如何在Spring Security中配置OAuth2登录功能。它定义了一个ClientRegistrationRepository
,并在HttpSecurity
中通过.oauth2Login()
配置OAuth2登录。这里使用了loginPage
、authorizationEndpoint
、redirectionEndpoint
和tokenEndpoint
方法来定制OAuth2授权和令牌的端点路径。
评论已关闭