首页 > 解决方案 > 如何拒绝没有特定角色的所有请求 - SpringBoot 安全配置

问题描述

我有以下 SpringBoot web 安全配置。对于授权,我想自动禁止身份验证不包括角色的所有请求ADMIN,但是这会拒绝所有请求,并且只选择 springExprFilter 中的SUPER_ADMIN属性,因此它投票拒绝访问。CUSTOMERdenyAll

我的配置中缺少什么?

@EnableWebSecurity
@RequiredArgsConstructor
@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  private final MemberDetailsService memberDetailsService;
  private final JwtRequestFilter jwtRequestFilter;

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(memberDetailsService).passwordEncoder(getPasswordEncoder());
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.headers()
        .disable()
        .csrf()
        .disable()
        .authorizeRequests()
        // permit all request for authentication
        .antMatchers("/v1/authenticate")
        .permitAll()
        .and()
        .authorizeRequests()
        // permit all request with the following list of roles
        // methods will enforce their own authorization logic
        .antMatchers("/v1/members/")
        .hasAnyAuthority("ADMIN", "CUSTOMER", "SUPER_ADMIN")
        .and()
        .authorizeRequests()
        .anyRequest()
        .denyAll()
        .and()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
  }

标签: javaspring-bootauthenticationspring-securityauthorization

解决方案


我发现弹簧安全配置表达式是正确的。问题是antmatcher.antMatchers("/v1/members/")不正确。这意味着将请求与/v1/members/不是预期功能的路径匹配。

对于任何感兴趣的人,我提出的要求是GET v1/members/:uuid

我应该使用通配符.antMatchers("/v1/members/**")来捕获对成员端点的所有请求。


推荐阅读