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 same for both types of requests.
So far I am not able to find a solution. In addition, the getAuthenticationManager() in CustomOAuth2Filter throws stackoverflow exception.
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);
}
}
user26662895 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.