Spring Security - antMatcher 的 POST 方法(不是 antMatchers)

App*_*evo 4 java spring spring-security spring-boot spring-config

我有两个配置:

@订单(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));
}
Run Code Online (Sandbox Code Playgroud)

@订单(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");
Run Code Online (Sandbox Code Playgroud)

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

编辑:

我需要这样的东西:

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

g00*_*00b 7

你可以这样做antMatchers()

http
    .antMatcher("/api/**")
        .authorizeRequests()
            .antMatchers(HttpMethod.POST, "/api/user").permitAll()
            .anyRequest().hasRole("USER")
Run Code Online (Sandbox Code Playgroud)

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

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

antMatchers(..)另一方面(内authorizeRequests(..))用于授权级别之间进行区分(哪些角色访问某些端点)。

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


但是,如果您确实需要对应该应用的安全配置类进行更精细的控制,那么您应该RequestMatcher按照评论中的说明使用。

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