我有一个 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
中定义多个 WebSecurityConfigurerAdapter
。 http://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/