我正在用Spring MVC构建一个CRM系统。现在我添加了对系统的REST支持,但由于某种原因,Spring Security将允许角色为"EMPLOYEE"的未经授权的用户访问POST方法(以在系统中创建新客户(。表单和身份验证一切正常。只是由于某些原因,特别是RestController的授权失败。
我使用PostgreSQL来存储客户和用户以及身份验证。
注意:我在REST中使用"/customer",并将其作为Web应用程序表单的入口点。
这是我的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映射到另一个路径,但没有成功
- 我还尝试将SecurityConfig拆分为多个入口点,但没有成功,出于某种原因,我也开始自动登录
- 在RestController中的Post方法之前添加了@Secured({"ROLE_MANAGER","ROLE_ADMIN"}(-结果相同
在我的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");
}
}
}