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.core.endpoint.OAuth2AuthorizationRequest;
@Configuration
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
private final ClientRegistrationRepository clientRegistrationRepository;
public OAuth2LoginSecurityConfig(ClientRegistrationRepository clientRegistrationRepository) {
this.clientRegistrationRepository = clientRegistrationRepository;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// 配置OAuth2登录注册路径
.oauth2Login()
.loginPage("/login")
.authorizationEndpoint()
.baseUri("/oauth2/authorize")
.and()
// 其他安全配置
.and()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login?logout")
.and()
.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}
public OAuth2AuthorizationRequest oauth2AuthorizationRequest(String registrationId, String redirectUri) {
OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode()
.state(UUID.randomUUID().toString().replaceAll("-", ""))
.clientId(clientRegistrationRepository.findByRegistrationId(registrationId).getClientId())
.authorizationUri(UriComponentsBuilder.fromUriString("http://localhost:8080/oauth2/authorize")
.queryParam("response_type", "code")
.queryParam("client_id", clientRegistrationRepository.findByRegistrationId(registrationId).getClientId())
.build().toUriString())
.redirectUri(redirectUri)
.scopes(Arrays.asList("openid", "profile", "email"))
.bui
评论已关闭