Spring MVC webapp + REST: 授权问题

问题描述 投票:0回答:1

我正在用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;
    }
}

更新:

  1. 我试着把RestController映射到另一个路径上--没用。
  2. 我还尝试了将SecurityConfig分割成多个入口点--不奏效,而且还因为某些原因开始自动登录。
  3. 在RestController的Post方法前添加了@Secured({"ROLE_MANAGER", "ROLE_ADMIN"})--结果相同。

似乎我的RestController中,Spring根本不关心用户的角色。

spring-mvc spring-security spring-rest
1个回答
0
投票

经过几个小时的研究和试错,一切都能如愿以偿.关键问题是方法路径中缺少星号。而不是 "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");
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.