java - 如何通过Java配置使用Spring Security实现多登录场景?

标签 java spring spring-security

我有一个 Spring Boot 应用程序。它有一个欢迎页面,用户可以在其中选择他们的登录类型,然后他们会被重定向到登录页面并根据他们的选择获得他们的角色。每个登录页面都提供不同外部 Web 服务的身份验证机制。我为一个场景配置了安全性,但如何为多个场景执行此操作?我应该使用多个安全配置还是同一安全配置中的所有配置来执行此操作?如果是这样怎么办?

SecurityConfig.java

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private CustomAuthenticationProvider cap;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/welcomeX").hasAuthority("X_USER")
                .and()
                .formLogin()
                .loginPage("/login")
                .loginPage("/main")
                .loginProcessingUrl("/welcome")
                .permitAll()
                .failureUrl("/login?error=true");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(cap);
    }

CustomAuthenticationProvider.java

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private ExternalService externalService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
       String username = authentication.getName();
       String password = authentication.getCredentials().toString();

       Response resp = externalService.authenticate(username, password);

       if (resp.isSuccess()) {
       List<GrantedAuthority> grantedAuths = new ArrayList<>();
    grantedAuths.add(new SimpleGrantedAuthority("X_USER"));
    Authentication auth = new UsernamePasswordAuthenticationToken(username, password, grantedAuths);
    return auth;
} else {
    return null;
}
    }
}

最佳答案

您可以在 @Configuration 中定义多个 WebSecurityConfigurerAdapterhttp://docs.spring.io/spring-security/site/docs/3.2.x/reference/htmlsingle/#multiple-httpsecurity

关于java - 如何通过Java配置使用Spring Security实现多登录场景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40233192/

相关文章:

java - 如何在 webdriver 中使用已打开的浏览器 Activity session

java - Android Cam 致命异常文件 URI 暴露

java - 序列化 - 不工作

java - Spring MVC 在调用 SpringStoredProcedure.execute() 后是否发出提交

java - Spring Cache 刷新过时的值

spring-boot - 白名单 '/' 端点不适用于 Spring Security 6

java - 将 char 放入 int 数组中是什么意思,它是 ASC 数字吗?

java - 为什么 Spring Security 的 BCrypt 实现使用 no-early-return equals 方法?

java - 如何在正在测试的另一个类中模拟类?

java - 如何在保持缓存自动配置的同时添加自定义@Cacheable缓存?