Configuring CSRF Protection in Spring Security for Internal and Third-Party Calls

How can I configure Spring Security to enforce CSRF against both backend-to-backend calls and external integrations? Internal API calls and third-party requests are token-challenged. Below is an alternative implementation:

@Configuration
@EnableWebSecurity
public class CustomSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity httpSec) throws Exception {
        httpSec.csrf()
               .csrfTokenRepository(CustomCookieTokenRepository.withNonHttpOnlyFlag())
               .requireCsrfProtectionMatcher(request -> {
                   Set<String> safeOps = new HashSet<>(Arrays.asList("GET", "HEAD", "OPTIONS"));
                   return !safeOps.contains(request.getMethod());
               });
    }
}
@RestController
public class VersionController {
    @GetMapping("/version")
    public String versionInfo() {
        return "Version 1.0 running";
    }
}
@RestController
public class SubmitController {
    @PostMapping("/{id}/submit")
    public String processSubmit(@PathVariable String id) {
        return "Submission for: " + id;
    }
}
@RestController
public class ChainController {
    @PostMapping("/{id}/chain")
    public String chainProcess(@PathVariable String id) {
        RestTemplate template = new RestTemplate();
        String target = "http://localhost:8080/api/" + id + "/submit";
        try {
            String reply = template.postForObject(target, null, String.class);
            return "Chain successful: " + reply;
        } catch (Exception e) {
            return "Chain failed";
        }
    }
}

In my experience, implementing CSRF protection for both internal and third-party services requires careful attention to token lifecycle management. It is important to ensure that CSRF tokens are not only generated and stored securely, but also propagated correctly during internal calls such as when using RestTemplate. Adjusting the default token repository and customizing the security matcher can provide the necessary flexibility. Additionally, thorough testing of all endpoints guarantees that back-end APIs remain secure, without inadvertently interfering with system integration or third-party interactions.