Search code examples
javaspringspring-bootspring-securityspring-authorization-server

Spring authorization server is not permitting access to my endpoint


When I send a POST REQUEST to the endpoint api/order/process/result I receive a 401 response from the spring boot resource server. I need help in identifying if I have well authorized my endpoint well to be called without an Authorization header (Bearer) in my Spring boot security configuration

@RestController
@RequestMapping("/api")
public class OrderController {
    private final static Logger LOGGER = LoggerFactory.getLogger(OrderController.class);
    private final OrderService orderService;

    public OrderController(OrderService orderService) {
        this.orderService = orderService;
    }
 @PostMapping(
            path = "/order/process/result",
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE
    )
    public String handleStkCallback(@RequestBody String result) {
        LOGGER.info(result);
        orderService.handleStkCallback(result);
        return "{\"responseCode\": \"0\"}";
    }
}
@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Value("${jwksUri}")
    private String jwksUri;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .cors().and().csrf().disable()
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers(POST, "/api/order/process/result").permitAll()
                        .anyRequest().authenticated()
                )
                .oauth2ResourceServer(oauth2 -> oauth2
                        .jwt(jwt -> jwt
                                .jwkSetUri(jwksUri)
                        )
                );
        return http.build();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);

        return source;
    }
}

Solution

  • Can you try to swap these 2 instructions "/api/order/process/result").permitAll() .anyRequest().authenticated() ?

    I think that the order matters, so try to first make all the endpoints to require auhtorization, then override it by declaring that specific endpoint to not require authorization