【发布时间】:2020-05-24 04:34:09
【问题描述】:
我正在尝试配置 Spring Security 并收到以下错误:
原因:java.lang.IllegalStateException: Can't configure antMatchers after anyRequest
这是我的SecurityConfig 班级:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter{
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(encodePWD());
}
@Override
protected void configure(HttpSecurity http) throws Exception{
http
.csrf().disable();
http
.httpBasic()
.and()
.authorizeRequests()
.antMatchers("/rest/**").permitAll()
.anyRequest().authenticated()
.and()
.authorizeRequests()
.antMatchers("/secure/**").hasAnyRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.permitAll();
http
.authorizeRequests()
.antMatchers("/login").permitAll();
}
@Bean
public BCryptPasswordEncoder encodePWD(){
return new BCryptPasswordEncoder();
}
}
如here 所述,我已经尝试致电httpSecurityauthorizeRequests().anyRequest().authenticated(),
仍然没有工作
...任何建议都会有所帮助。
【问题讨论】:
-
不是那个,
http.httpBasic() .and() .authorizeRequests() .antMatchers("/rest/**") .permitAll() .and() .antMatchers("/secure/**") .hasAnyRole("ADMIN") .anyRequest() .authenticated() .and() .formLogin().permitAll();这边。 -
谢谢你....现在它的工作
-
请问“http.csrf().disable()”到底是做什么的?我在很多地方都看到过。我知道 CSRF 的基础知识,但为什么我们需要在这里禁用它?如果那条线不存在会怎样?
标签: java spring spring-security