Spring Security-antMatcher(而非antMatchers)的POST方法

时间:2019-03-25 13:21:46

标签: java spring spring-boot spring-security spring-config

我有两种配置:

@Order(1)

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.antMatcher("/api/**")
        .authorizeRequests()
        .anyRequest().hasRole("USER")
        .and()
        .httpBasic()
        .and()
        .csrf().disable()
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .exceptionHandling()
        .authenticationEntryPoint(new ApiAuthenticationEntryPoint(objectMapper));
}

@Order(2)

http.authorizeRequests()
    .antMatchers("/product/**").hasRole(SecurityRoles.USER)
    .and()
    .formLogin()
    .loginPage("/login")
    .loginProcessingUrl("/authenticateTheUser")
    .successHandler(customAuthenticationSuccessHandler)
    .permitAll()
    .and()
    .logout()
    .permitAll()
    .and()
    .exceptionHandling()
    .accessDeniedPage("/access-denied");

我需要添加功能以在没有身份验证的情况下向REST端点 /api/users 注册新用户。其他 /api/** 端点应保留基本身份验证。这该怎么做?我看不到方法antMatcher带有选择http方法类型的选项。

编辑:

我需要这样的东西:

http.antMatcher("/api/users", HttpMethod.POST.toString).permitAll()
    .and()
    .antMatcher("/api/**")
            .authorizeRequests()
            .anyRequest().hasRole("USER")
(...)

1 个答案:

答案 0 :(得分:1)

不过,您可以使用antMatchers()来做到这一点:

http
    .antMatcher("/api/**")
        .authorizeRequests()
            .antMatchers(HttpMethod.POST, "/api/user").permitAll()
            .anyRequest().hasRole("USER")

antMatcher(..)antMatchers(..)之间的区别在于,当您拥有单独的安全配置类时,将使用antMatcher(..)。当您需要区分以下内容时,这可能是必要的:

  • 身份验证机制(表单登录,基本身份验证等)
  • CSRF处理
  • 会话管理
  • 过滤器
  • 用户详细信息服务
  • ...

另一方面,antMatchers(..)(在authorizeRequests(..)内)用于区分授权级别(哪些角色有权访问特定端点)。

在您的情况下,配置属于后者,因为您只需区分POST /api/user端点的权限即可。


但是,如果您确实需要进一步控制应应用的安全配置类,则应使用RequestMatcher,如注释中所述。

此接口只有一个HttpServletRequest参数,希望您返回boolean。由于HttpServletRequest包含您需要的所有信息,例如路径和HTTP方法,因此您可以适当地调整应该应用哪个配置类。但是,在这种情况下是没有必要的。