javaspringspring-security

Anonymous SecurityContext initiated when using SpringSecurity with permitted patterns


I am using Spring Security 6.4.8. I need to allow an endpoint for initiation of the login, say /fun, in which I need to have certain logic (e.g. do something with a passed parameter).

Therefore, I need unauthenticated call to this controller.

@RestController
public class FunController {

    @GetMapping("/fun")
    public ResponseEntity<String> fun() {
        return ResponseEntity.ok("FUN!");
    }
}

I can't find a way to get a call to it (in reality it will be another service calling mine), that would not trigger the anonymous SecurityContext which will joyfully initiate the login process before my controller has done its job.

More specifically, I get

o.s.security.web.FilterChainProxy        : Securing GET /fun
o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext

My filter chain looks like this:

 public SecurityFilterChain filterChain(HttpSecurity http, RestClient restClient) throws Exception {

        http
                .authorizeHttpRequests(
                        requests ->
                                requests
                                        .requestMatchers("/", "/fun", "/login", "/login?error")
                                        .permitAll()
                                        .anyRequest()
                                        .authenticated())
                .oauth2Login(
                        oauth ->
                                oauth
                                        .defaultSuccessUrl("/authorized")
                                        ...)
                //.oauth2Client(Customizer.withDefaults());

        return http.build();

I read that Spring will at least start the anonymous security filter. I there a way I can allow /fun be reached by services within my network?


Solution

  • So, this was a very unexpected problem, quite a goofy one.

    In my application I had

    @ComponentScan(basePackages = {"path.to.a.package.from.external.module.with.generic.spring.auth.components",
     "path.to.a.package.with.local.spring.security.customizations.with.typo"})
    

    Note the part with.typo - I was completely shadowing my custom implementation, including my custom security chain from above. Interestingly, Spring did not complain about this problem. Maybe this is expected because the package might exist, but providing no components? I switched to Idea Ultimate in the meantime and now it shows me such packages, but I just wonder if this is fair tradeoff, given the fact it might cover bugs extremely well.