In one of our services, it is possible to get requests from two sources, internal (within our cluster) and external. For internal requests, the request needs to be validated using JWT token. For external ones there are just headers that need to be checked.
I want to use the Spring default mechanisms for oauth2 where it just validates the token automatically and if the token is not present then check the headers (or vice versa).
The complication is the API path (endpoints) is the same for both types of requests.
So far, I am not able to find a solution. In addition, the getAuthenticationManager() in CustomOAuth2Filter throws a StackOverflowException.
I have this main configuration class
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfiguration {
@Bean
public CustomOAuth2Filter customOAuth2Filter(AuthenticationManager authenticationManager) {
CustomOAuth2Filter filter = new CustomOAuth2Filter(authenticationManager);
return filter;
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http, AuthenticationManager authenticationManager) throws Exception {
http
.authorizeRequests()
.anyRequest().permitAll() // Allow unauthenticated access by default
.and()
.addFilterBefore(customOAuth2Filter(authenticationManager), BasicAuthenticationFilter.class) // Add custom filter before basic authentication
.oauth2ResourceServer(oauth2 -> oauth2
.jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter())));
return http.build();
}
@Bean
public JwtAuthenticationConverter jwtAuthenticationConverter() {
JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
grantedAuthoritiesConverter.setAuthoritiesClaimName("groups");
grantedAuthoritiesConverter.setAuthorityPrefix("");
JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
return jwtAuthenticationConverter;
}
}
Then I have added a filter that will check if the headers are present, if they are then just use them, if not then do JWT validation.
@Component
public class CustomOAuth2Filter extends AbstractAuthenticationProcessingFilter {
public CustomOAuth2Filter(AuthenticationManager authenticationManager) {
super("/path/**");
setAuthenticationManager(authenticationManager);
}
@Override
protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
String authHeader = request.getHeader("Authorization");
return authHeader != null && authHeader.startsWith("Bearer ");
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
extractUserInfo(request);
if (SecurityContextHolder.getContext().getAuthentication() != null) {
return SecurityContextHolder.getContext().getAuthentication();
}
String token = request.getHeader("Authorization");
if (token != null && token.startsWith("Bearer ")) {
token = token.substring(7);
BearerTokenAuthenticationToken authenticationToken = new BearerTokenAuthenticationToken(token);
return getAuthenticationManager().authenticate(authenticationToken);
}
return null; // No token present, return null to proceed without authentication
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
SecurityContextHolder.getContext().setAuthentication(authResult);
chain.doFilter(request, response);
}
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
SecurityContextHolder.clearContext();
// chain.doFilter(request, response); // Proceed without authentication
}
protected void extractUserInfo(HttpServletRequest request) throws ServletException, IOException {
String username = extractHeader(request, "user");
String roleStr = extractHeader(request, "roles");
if (username == null || roleStr == null || roleStr.isBlank()) {
return;
}
List<String> roles = Arrays.asList(roleStr.split(","));
List<GrantedAuthority> grantedAuthorities = roles.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
MyUser user = new MyUser(username, "", grantedAuthorities);
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(auth);
}
private String extractHeader(HttpServletRequest request, String extractValue) {
return request.getHeader(extractValue);
}
}
4
You should define a SecurityFilterChain
for each security mechanism, each with a distinct @Order
and all but the last one in order with a SecurityMatcher
.
For instance:
@Bean
@Order(Ordered.LOWEST_PRECEDENCE - 1)
SecurityFilterChain resourceServerFilterChain(HttpSecurity http, Converter<Jwt, ? extends AbstractAuthenticationToken> jwtAuthenticationConverter)
throws Exception {
http.securityMatcher((HttpServletRequest request) -> {
return Optional.ofNullable(request.getHeader(HttpHeaders.AUTHORIZATION)).map(h -> {
return h.toLowerCase().startsWith("bearer ");
}).orElse(false);
});
http.oauth2ResourceServer(rs -> rs.jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter)));
http.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS)).csrf(csrf -> csrf.disable());
http.authorizeHttpRequests(SecurityConfiguration::authorize);
return http.build();
}
@Bean
@Order(Ordered.LOWEST_PRECEDENCE)
SecurityFilterChain headerBasedFilterChain(HttpSecurity http, Converter<Jwt, ? extends AbstractAuthenticationToken> jwtAuthenticationConverter)
throws Exception {
// Configure security for external requests
http.authorizeHttpRequests(SecurityConfiguration::authorize);
return http.build();
}
static void authorize(AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizationManagerRequestMatcherRegistry requests) {
requests.anyRequest().permitAll();
}
With the above, all requests with a Bearer
authorization header are processed by the first filter-chain. All other requests (those not having a Bearer
header, which includes anonymous requests) are processed by the second filter chain.