如何在Java配置中使用Spring Security进行多种登录方案?

时间:2016-10-25 06:51:13

标签: 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;
}
    }
}

1 个答案:

答案 0 :(得分:2)

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