1. 首页
  2. 软件开发
  3. Spring Security实现单点登录(SSO)

Spring Security实现单点登录(SSO)

  • 发布于 2024-08-17
  • 1 次阅读

实现单点登录(SSO)可以让用户在多个应用程序中使用相同的凭证进行登录,提供更便捷的用户体验。

1. 配置SSO服务提供方(SP)

在每个应用程序中配置Spring Security作为SSO服务提供方,以验证用户凭证。

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
   

    @Override
    protected void configure(HttpSecurity http) throws Exception {
   
        http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
   
        auth
            .inMemoryAuthentication()
                .withUser("user").password("{noop}password").roles("USER");
    }
}

2. 配置SSO认证中心(IdP)

创建一个单独的应用作为SSO认证中心,负责处理用户的登录和认证。

@Configuration
@EnableWebSecurity
public class IdpSecurityConfig extends WebSecurityConfigurerAdapter {
   

    @Override
    protected void configure(HttpSecurity http) throws Exception {
   
        http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
   
        auth
            .inMemoryAuthentication()
                .withUser("user").password("{noop}password").roles("USER");
    }
}

3. 配置单点登录(SSO)

使用Spring Security的 SsoConfigurer 来配置单点登录,将SSO服务提供方和SSO认证中心连接起来。

@Configuration
@EnableWebSecurity
public class SsoConfig extends WebSecurityConfigurerAdapter {
   

    @Override
    protected void configure(HttpSecurity http) throws Exception {
   
        http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .sso();
    }
}

通过以上配置,可以实现基于Spring Security的单点登录(SSO)功能。用户可以在SSO认证中心登录后,访问其他应用程序时无需重新登录,提高了用户体验并简化了管理。

原文链接: https://blog.csdn.net/2401_82884096/article/details/138249058