我正在尝试使用 Spring Security,并且有一个用例,我希望不同的登录页面和不同的 URL 集得到保护。
这是我的配置:
@Configuration
@Order(1)
public static class ProviderSecurity extends WebSecurityConfigurerAdapter{
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.antMatchers("/admin/login").permitAll()
.antMatchers("/admin/**").access("hasRole('BASE_USER')")
.and()
.formLogin()
.loginPage("/admin/login").permitAll()
.defaultSuccessUrl("/admin/home")
.failureUrl("/admin/login?error=true").permitAll()
.usernameParameter("username")
.passwordParameter("password")
.and()
.csrf()
.and()
.exceptionHandling().accessDeniedPage("/Access_Denied");
}
}
@Configuration
@Order(2)
public static class ConsumerSecurity extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/consumer/login").permitAll()
.antMatchers("/consumer/**").access("hasRole('BASE_USER')")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/consumer/login").permitAll()
.defaultSuccessUrl("/consumer/home")
.failureUrl("/consumer/login?error=true").permitAll()
.usernameParameter("username")
.passwordParameter("password")
.and().csrf()
.and()
.exceptionHandling().accessDeniedPage("/Access_Denied");
}
}
这些类是另一个类的内部类MultipleHttpSecurityConfig
有注释的@EnableWebSecurity
.
安全性为admin/**
工作正常,但没有一个consumer/**
页面受到保护,登录页面不会发生重定向。我搜索过其他答案,但没有一个有效。
看着那(这Spring安全参考 http://docs.spring.io/spring-security/site/docs/4.2.x/reference/htmlsingle/#multiple-httpsecurity:
@EnableWebSecurity
public class MultiHttpSecurityConfig {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) { 1
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER").and()
.withUser("admin").password("password").roles("USER", "ADMIN");
}
@Configuration
@Order(1) 2
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/**") 3
.authorizeRequests()
.anyRequest().hasRole("ADMIN")
.and()
.httpBasic();
}
}
@Configuration 4
public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin();
}
}
}
1 正常配置身份验证
2 创建一个实例WebSecurityConfigurerAdapter
其中包含@Order
指定哪个WebSecurityConfigurerAdapter
应首先考虑。
3 The http.antMatcher
指出这HttpSecurity
仅适用于以下开头的 URL/api/
4 创建另一个实例WebSecurityConfigurerAdapter
。如果 URL 不是以以下内容开头/api/
将使用此配置。此配置是在之后考虑的ApiWebSecurityConfigurationAdapter
因为它有一个@Order
之后的值1
(no @Order
默认为最后)。
未使用您的第二个配置,因为您的第一个配置匹配/**
(no antMatcher
配置)。你的第一个配置仅限制/admin/**
,默认情况下允许所有其他 URL。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)