Scorpio76
Scorpio76

Reputation: 33

Spring OAuth2.0 : Spring Authorization Server 1.0 and Resource server in the same boot application

I'm struggling to use the very same Spring Boot 3.0 application as both authentication server and resource server, but until now, I've not been able to make the whole thing working.

First, I defined a very simple RestController:

@RestController
@RequestMapping("api")
public class PublicAPI {
        
    @GetMapping("/apitest")
    public String test(Principal principal) {
        return " This is a test ==>";
    }
}

Then, essentially following the code found in a Sample project of Spring, I managed to setup my boot app as Spring Authorization Server. I'm able to use Postman to get the authentication token using Oauth2 flow: I'm redirected to Spring's standard login page, I log in with credentials, and I get the Token.

Problem is, if I try to GET http://localhost:9000/api/apitest` using provided token, I get a 401 response from Spring boot.

This is my Security Configuration:

@Bean 
    @Order(1)
    public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http, CorsConfiguration configCors) throws Exception {
        OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
        http.getConfigurer(OAuth2AuthorizationServerConfigurer.class).oidc(Customizer.withDefaults());
        http
            .exceptionHandling((exceptions) -> exceptions
                .authenticationEntryPoint(
                    new LoginUrlAuthenticationEntryPoint("/login"))
            );
        http.cors().configurationSource(request -> configCors);
        return http.build();
    }

    @Bean
    @Order(2)
    SecurityFilterChain apiFilter(HttpSecurity http) throws Exception {
        http
            .securityMatcher("/api/**")
                .authorizeHttpRequests()
                    .requestMatchers("/api/**").authenticated()
                    .and()
            .oauth2ResourceServer()
                .jwt();
        return http.build();
    }
    
    @Bean 
    @Order(3)
    public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http, CorsConfiguration configCors) throws Exception {
        http
            .securityMatcher("/oauth2/**", "/login")
            .authorizeHttpRequests()
                .requestMatchers("/login", "/oauth2/**")
                .authenticated()
                .and()
            .formLogin(Customizer.withDefaults());
        http.cors().configurationSource(request -> configCors);
        return http.build();
    }
    
    @Bean
    public CorsConfiguration corsConfiguration() throws Exception {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowCredentials(true);
        configuration.setAllowedOriginPatterns(List.of("*"));
        configuration.setAllowedMethods(List.of("*"));
        configuration.setAllowedHeaders(List.of("*"));
        return configuration;
    }

If I try to access another Spring API in a different Spring Boot application which uses the first one as Authentication Server I get no errors. Pretty sure that there's something wrong my configuration... any hint will be greatly appreciated !

Upvotes: 3

Views: 570

Answers (1)

Scorpio76
Scorpio76

Reputation: 33

At the very end, it turned out that another filter has been configured:

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class LoopbackIpRedirectFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        if (request.getServerName().equals("localhost") && request.getHeader("host") != null) {
            UriComponents uri = UriComponentsBuilder.fromHttpRequest(new ServletServerHttpRequest(request))
                    .host("127.0.0.1").build();
            response.sendRedirect(uri.toUriString());
            return;
        }
        filterChain.doFilter(request, response);
    }

}

Removing the LoopbackIpRedirectFilter problem was fixed

Upvotes: 0

Related Questions