我正在用Spring MVC构建一个CRM系统。现在我为系统添加了REST支持,但是Spring Security出于某种原因,允许未经授权的用户使用 "EMPLOYEE "角色访问POST方法(在系统中创建一个新客户)。只是由于某些原因,RestController的授权失败了。
我使用PostgreSQL来存储客户和用户以及认证。
注意:我使用 "customer "作为REST和webapp表单的入口点。
以下是我的SecurityConfig
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(HttpMethod.GET, "/customer").hasRole("EMPLOYEE")
.antMatchers(HttpMethod.POST, "/customer").hasAnyRole("MANAGER", "ADMIN")
.antMatchers("/customer/showForm*").hasAnyRole("MANAGER", "ADMIN")
.antMatchers("/customer/save*").hasAnyRole("MANAGER", "ADMIN")
.antMatchers("/customer/delete").hasRole("ADMIN")
.antMatchers("/customer/**").hasRole("EMPLOYEE")
.antMatchers("/resources/**").permitAll()
.and()
.httpBasic()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/authenticate")
.permitAll()
.and()
.logout().permitAll()
.and()
.exceptionHandling().accessDeniedPage("/access-denied")
.and()
.csrf().disable();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider auth = new DaoAuthenticationProvider();
auth.setUserDetailsService(userService);
auth.setPasswordEncoder(passwordEncoder());
return auth;
}
}
这是我的RestController。
@RestController
@RequestMapping("/customer")
public class CustomerRestController {
@Autowired
private CustomerService customerService;
@GetMapping
public List<Customer> getCustomers() {
return customerService.getCustomers();
}
@GetMapping("/{customerId}")
public Customer getCustomer(@PathVariable int customerId) {
Customer customer = customerService.getCustomer(customerId);
if (customer == null) throw new CustomerNotFoundException("Customer not found: id = " + customerId);
return customer;
}
@PostMapping
public Customer addCustomer(@RequestBody Customer customer) {
customer.setId(0);
customerService.saveCustomer(customer);
return customer;
}
}
更新:
似乎我的RestController中,Spring根本不关心用户的角色。
经过几个小时的研究和试错,一切都能如愿以偿.关键问题是方法路径中缺少星号。而不是 "customer",它必须是 "customer**".我也改变了一下Web表单和REST支持的路径,以避免混淆,使支持更容易.无论如何,这里是更新的SecurityConfig。
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider auth = new DaoAuthenticationProvider();
auth.setUserDetailsService(userService);
auth.setPasswordEncoder(passwordEncoder());
return auth;
}
@Configuration
@Order(1)
public static class ApiSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public AuthenticationEntryPoint entryPoint() {
return new CustomAuthenticationEntryPoint();
}
@Bean
public AccessDeniedHandler accessDeniedHandler() {
return new CustomAccessDeniedHandler();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().antMatcher("/api/**")
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/api/customers/**").hasRole("EMPLOYEE")
.antMatchers(HttpMethod.POST, "/api/customers/**").hasAnyRole("MANAGER", "ADMIN")
.and()
.httpBasic()
.authenticationEntryPoint(entryPoint())
.and()
.exceptionHandling().accessDeniedHandler(accessDeniedHandler())
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
@Configuration
@Order(2)
public static class FormSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/customer/showForm*").hasAnyRole("MANAGER", "ADMIN")
.antMatchers("/customer/save*").hasAnyRole("MANAGER", "ADMIN")
.antMatchers("/customer/delete").hasRole("ADMIN")
.antMatchers("/customer/**").hasRole("EMPLOYEE")
.antMatchers("/resources/**").permitAll()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/authenticate")
.permitAll()
.and()
.logout().permitAll()
.and()
.exceptionHandling().accessDeniedPage("/access-denied");
}
}
}