我有一个在端口8081上运行此配置的Spring Boot App:

@Configuration
@EnableMethodSecurity
public class WebSecurityConfig { // extends WebSecurityConfigurerAdapter {

    private final JwtUtils jwtUtils;
    private final UserDetailsServiceImpl userDetailsService;

    private final AuthEntryPointJwt unauthorizedHandler;

    public WebSecurityConfig(JwtUtils jwtUtils,
                             UserDetailsServiceImpl userDetailsService,
                             AuthEntryPointJwt unauthorizedHandler) {

        this.jwtUtils = jwtUtils;
        this.userDetailsService = userDetailsService;
        this.unauthorizedHandler = unauthorizedHandler;
    }

    @Bean
    public AuthTokenFilter authenticationJwtTokenFilter() {
        return new AuthTokenFilter(jwtUtils, userDetailsService);
    }



    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();

        authProvider.setUserDetailsService(userDetailsService);
        authProvider.setPasswordEncoder(passwordEncoder());

        return authProvider;
 }


    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf(AbstractHttpConfigurer::disable)
                .exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler))
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authorizeHttpRequests(auth ->
                        auth.requestMatchers("/api/auth/**").permitAll()
                                .requestMatchers("/actuator/**").permitAll()
                                .requestMatchers("/actuator/metrics").permitAll()
                                .requestMatchers("/api/languages").permitAll()
                                .requestMatchers("/api/actuator/health").permitAll()
                                .requestMatchers("/api/auth/sendMailOTP").permitAll()
                                .requestMatchers("/api/messages/**").permitAll()
                                .requestMatchers("/api/auth/socialSignin").permitAll()
                                .requestMatchers("/api/geoDetails").permitAll()
                                .requestMatchers("/api/legalinfo/**").permitAll()
                                .requestMatchers("/api/legalinfo/*").permitAll()
                                .requestMatchers("/api/legalinfo/eula").permitAll()
                                .requestMatchers("/api/users/uploadFile/**").permitAll()
                                .requestMatchers("/api/users/sendEmail").permitAll()
                                .requestMatchers("/api/legalinfo/privacy").permitAll()
                                .requestMatchers("/api/changeuserpassword").permitAll()
                                .requestMatchers("/api/forgotmypassword").permitAll()
                                .requestMatchers("/api/validateEmail").permitAll()
                                .requestMatchers("/api/checkToken").permitAll()
                                .requestMatchers("/api/checkOTPToken").permitAll()
                                .anyRequest().authenticated()
                );

        http.authenticationProvider(authenticationProvider());
        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }
}

正在做的事:http://172.105.90.17:8081/actuator/health

我得到了:

{
  "status": "UP"
}

但访问:http://172.105.90.17:8081/actuator/metrics

我收到:

{
  "message": "Full authentication is required to access this resource"
}

在控制台中:

2024-01-24 06:47:28.884 DEBUG [] o.s.b.f.s.DefaultListableBeanFactory@registerDependentBeans(952) - Autowiring by type from bean name 'webEndpointServletHandlerMapping' via factory method to bean named 'management.endpoints.web-org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties'
2024-01-24 06:47:28.884 DEBUG [] o.s.b.f.s.DefaultListableBeanFactory@registerDependentBeans(952) - Autowiring by type from bean name 'webEndpointServletHandlerMapping' via factory method to bean named 'environment'
2024-01-24 06:47:28.891 INFO  [] o.s.b.a.e.web.EndpointLinksResolver@<init>(58) - Exposing 1 endpoint(s) beneath base path '/actuator'
2024-01-24 06:47:28.905 DEBUG [] o.s.b.f.s.DefaultListableBeanFactory@getSingleton(225) - Creating shared instance of singleton bean 'controllerEndpointHandlerMapping'

推荐答案

你的问题可以分为这两个问题:

  1. How to expose actuator endpoints and make them remotely accessible over HTTP?
  2. How to make them accessible without need to login?

Solution of problem 1.

默认情况下,只有health终结点启用并通过HTTP公开.要包括所有可用终端,请将其添加到application.properties:

management.endpoints.web.exposure.include=*

如果您希望shutdown端点也可用,请添加以下内容:

management.endpoint.shutdown.enabled=true

如果你想改变默认的前缀actuator,你可以添加这个:

management.endpoints.web.base-path=/manage

使用以上设置,显示所有SpringBean的URL将如下所示:

http://localhost:8081/manage/beans

Solution of problem 2.

如果启用了Spring Boot Security(如本例所示),则无需登录即可访问health个端点.您可以通过将/manage/**添加到questMatcher块来覆盖此默认行为.大概是这样的:

    .authorizeHttpRequests((requests) -> requests
        .requestMatchers("/manage/**").permitAll()
        .anyRequest().authenticated()
    )

上面的内容不是很好.前缀manage在这里是硬编码的.如果后来有人更改了application.properties中的前缀怎么办?

最好改用专用的工厂类EndpointRequest.保持特定于应用程序的SecurityFilterChange Bean不变,并为执行器添加另一个Bean:

    @Order(Ordered.HIGHEST_PRECEDENCE)
    @Bean
    public SecurityFilterChain actuatorFilterChain(HttpSecurity http) throws Exception {
        http.securityMatcher(EndpointRequest.toAnyEndpoint().excluding(ShutdownEndpoint.class));
        http.authorizeHttpRequests((requests) -> requests.anyRequest().permitAll());
        return http.build();
    }

在上面的示例中,除shutdown以外的所有终端对所有人都可访问.

请注意@Order个注释.这一点很重要,因为使用了SecurityMatcher.

在服务器日志(log)中,您将看到类似以下内容:

EndpointLinksResolver      : Exposing 14 endpoint(s) beneath base path '/manage'
DefaultSecurityFilterChain : Will secure EndpointRequestMatcher includes=[*], excludes=[shutdown]...
DefaultSecurityFilterChain : Will secure any request with...

Spring Boot Documentation为基准.

Java相关问答推荐

是否有一种格式模式,可以在除0之外的数字前面有正负符号?

使用ExecutorService时在ThreadFactory中触发自定义newThread函数

如何计算内循环的时间复杂度?

为什么一个java函数会返回一个作为参数传递给它的对象?

无法传递消费者<;>;实例

';com.itextpdf.ext.html.WebColors已弃用

扩展到弹出窗口宽度的JavaFX文本字段

使用Spring Boot3.2和虚拟线程的并行服务调用

GSON期间的Java类型擦除

如何让JVM在SIGSEGV崩溃后快速退出?

如何在Spring Boot中创建可以将值传递给配置的&Enable&Quot;注释?

何时调用密封层次 struct 的switch 中的默认情况

Java.time.OffsetDateTime的SQL Server数据库列类型是什么?

H2数据库仅支持%1个结果集?

Cucumber java-maven-示例表-未定义一步

如何修复Spring Boot应用程序中的RestDocumentationGenerationException:java.io.FileNotFoundException:/curl-request.adoc(只读文件系统)?

spring 更新多项管理关系

@此处不能应用可为null的批注

如何使用Jackson读取以方括号开头的JSON?

窗口启动后不久,从java.awt.Graphics disapear创建的矩形