Spring Webflux Security 只允许一个 URL

Dha*_*pil 3 java spring spring-security spring-webflux

我想允许在特定控制器中定义的所有 url,除了一个。

假设我的控制器公开了 3 个带有基本 url 的 url /users

  1. "/" 列出所有用户
  2. "/{id}" 按 id 列出用户
  3. "/admin" 获取用户的管理员级别详细信息。

我想允许除最后一个用户之外的任何用户访问 1 和 2 个 url。

我一直在做这样的事情

@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
    http.authorizeExchange()
        .pathMatchers("/users/**")
        .permitAll()
        .pathMatchers("/users/admin")
        .hasRole("ADMIN")
        .anyExchange()
        .authenticated()
        .and()
        .httpBasic()
        .and()
        .formLogin();
    return http.build();
}
Run Code Online (Sandbox Code Playgroud)

但它不起作用。我也试过相反的,即

@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
    http.authorizeExchange()
        .pathMatchers("/users/admin")
        .hasRole("ADMIN")
        .anyExchange()
        .authenticated()
        .pathMatchers("/users/**")
        .permitAll()
        .and()
        .httpBasic()
        .and()
        .formLogin();
    return http.build();
}
Run Code Online (Sandbox Code Playgroud)

这也不起作用,说明因为anyExchange()已注册下一个pathMatcher无法访问。

Dha*_*pil 7

我找到了解决方案。 anyExchange()authenticated()导致了这个问题。anyExchange()不允许进一步添加任何路径匹配器,authenticated()并使整个应用程序受到保护,从而导致每个 url 提示进行身份验证。

删除这两个工作。

@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
    http.authorizeExchange()
        .pathMatchers("/users/admin/**")
        .hasRole("ADMIN")
        .pathMatchers("/**").permitAll()
        .and().httpBasic();
    return http.build();
}
Run Code Online (Sandbox Code Playgroud)