Spring Boot 3 极速搭建OAuth2认证框架
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.oauth2.server.authorization.client.InMemoryRegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
@Configuration
public class OAuth2AuthorizationServerConfig {
@Bean
public RegisteredClientRepository registeredClientRepository() {
// 这里可以从数据库或其他存储中加载注册客户端信息
return new InMemoryRegisteredClientRepository(registeredClient());
}
private RegisteredClient registeredClient() {
// 创建一个内存中的注册客户端
// 实际应用中应该从数据库或配置中读取
return RegisteredClient.withId("registered-client-id")
.clientId("client-id")
.clientSecret({secret})
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
.redirectUri("http://127.0.0.1:8080/login/oauth2/code/custom-client")
.scope("read")
.scope("write")
.clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build())
.build();
}
@Bean
public AuthenticationManager authenticationManager() throws Exception {
return
评论已关闭