我正在尝试学习Spring Security并创建了一个简单的控制器。我想为未经授权的用户启用POST到/ all端点,并为具有USER角色的用户启用POST到/ user。由于某种原因,我的代码总是返回未经授权的403。
控制器
public class Controller {
@PostMapping("/all")
public ResponseEntity<Object> all() {
return new ResponseEntity<>("all", HttpStatus.OK);
}
@PostMapping("/user")
public ResponseEntity<Object> user() {
return new ResponseEntity<>("user", HttpStatus.OK);
}
}
安全配置
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/all").permitAll()
.antMatchers(HttpMethod.POST, "/user").hasRole("USER");
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("user").roles("USER");
}
}
答案 0 :(得分:1)
httpBasic()
)BCryptPasswordEncoder
)将它们放在一起,您的配置应如下所示:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/all").permitAll()
.antMatchers(HttpMethod.POST, "/user").hasRole("USER")
.and().httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user")
.password(encoder().encode("user"))
.roles("USER");
}
@Bean
public PasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
}