SpringBoot Security OAuth2实现单点登录SSO(附源码)
以下是一个简化的Spring Boot 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.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.DefaultOAuth2ClientContext;
import org.springframework.security.oauth2.client.web.OAuth2ClientContext;
@Configuration
public class OAuth2LoginConfig extends WebSecurityConfigurerAdapter {
private final ClientRegistrationRepository clientRegistrationRepository;
public OAuth2LoginConfig(ClientRegistrationRepository clientRegistrationRepository) {
this.clientRegistrationRepository = clientRegistrationRepository;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.oauth2Login()
.clientRegistrationRepository(clientRegistrationRepository)
.authorizationEndpoint()
.baseUri("/oauth2/authorize")
.and()
.redirectionEndpoint()
.baseUri("/oauth2/callback/*");
}
// 注册ClientRegistrationRepository
// 这通常是通过配置文件或者数据库来完成的,这里为了简化,我们直接在代码中定义
// 实际应用中,应该从外部配置加载
@Bean
public ClientRegistrationRepository clientRegistrationRepository() {
ClientRegistration googleClient = ClientRegistration.withRegistrationId("google")
.clientId("client-id")
.clientSecret("client-secret")
.clientName("Google")
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri("{baseUrl}/oauth2/callback/{registrationId}")
.scope(OidcScopes.OPENID, OidcScopes.EMAIL, OidcScopes.PROFILE)
.authorizationUri("https://accounts.google.com/o/oauth2/v2/auth")
.tokenUri("https://www.googleapis.com/oauth2/v4/token")
评论已关闭