Enabling Spring Security on app fails health check
search cancel

Enabling Spring Security on app fails health check

book

Article ID: 298424

calendar_today

Updated On:

Products

VMware Tanzu Application Service for VMs

Issue/Introduction

You can turn on security on your app by simply adding this configuration on your Spring application
 
application.frameworks.security.enabled=true

After adding this configuration you noticed that your app is failing on health check. On this example the app is configured with HTTP health check on endpoint /actuator/health
 
2022-11-18T10:21:23.45+0100 [HEALTH/0] ERR Failed to make HTTP request to '/actuator/health' on port 8080: received status code 401 in 5ms 2022-11-18T10:21:23.45+0100 [CELL/0] ERR Failed after 3m1.112s: readiness health check never passed.


Environment

Product Version: 2.13

Resolution

Since you enabled  spring security there is an additional filter added on your app. Each request goes through a security filter  and checks for each request against security rules. By default Spring security secures each endpoint in your app by default.

You would need to add custom security configuration that allows unauthenticated access to the endpoints i.e health checks as shown in the following example:
package com.example.securingweb;
...

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

	@Bean
	public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
		http
			.authorizeHttpRequests((requests) -> requests
				.requestMatchers("/actuator/health").permitAll()
				.anyRequest().authenticated()
			)
			.formLogin((form) -> form
				.loginPage("/login")
				.permitAll()
			)
			.logout((logout) -> logout.permitAll());

		return http.build();
	}
	
}

In the example above path /actuator/health is configured to not require any authentication in order to pass TAS health check. All other paths must be authenticated.