maven 引入:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

核心类:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 监控API校验账号密码
 * @author: mengxc
 * @date: 2022/08/24 15:54
 */
@EnableWebFluxSecurity
public class WebSecurityConfig {
    @Bean
    SecurityWebFilterChain webFluxSecurityFilterChain(ServerHttpSecurity http) throws Exception {
        http.authorizeExchange().pathMatchers("/monitor/**").hasRole("ADMIN")
                .anyExchange().permitAll().and().cors().and()
                .httpBasic().and()
                .csrf().disable();
        return http.build();
    }
}

配置属性

management.endpoints.web.exposure.include=*
management.endpoints.web.base-path=/monitor
spring.security.user.name=mhuang
spring.security.user.password=huangmiao
spring.security.user.roles=ADMIN