Search code examples
javaspring-bootspring-securityspring-oauth2

Spring security failing to block the URLs


I have the following scenario where I have to allow only a particular URL and deny others. But I am not sure why its allowing both URLs

@Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        try{
            return http
                    .requestMatcher(new AntPathRequestMatcher("/RemoteHandlerServices/Handle"))
                        .authorizeHttpRequests(r -> r
                            .antMatchers("/RemoteHandlerServices/Handle").authenticated())
                    .requestMatcher(new AntPathRequestMatcher("/OtherHandlerServices/Test"))
                        .authorizeHttpRequests(r -> r
                            .antMatchers("/OtherHandlerServices/Test").denyAll()
                            .anyRequest().denyAll()
                    )
                    .build();

    } catch(Exception e){
            throw new RuntimeException("Authentication is failed");
        }
    }

Could someone explain me why this is happening?


Solution

  • You can try to substitute your filterChain with this one:

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(url -> url
                .antMatchers("/RemoteHandlerServices/Handle").authenticated()
                .antMatchers("/OtherHandlerServices/Test").denyAll()
                .anyRequest().authenticated());
    return http.build();
    

    Pay attention that from Spring Security 5.8 the antMatchers (with some others) method has been deprecated and you should use requestMatchers. From Spring Security 6 they have been removed.

    Remember that, by default, the first matching filter is the one that is applied to the url, so the next ones are discard.

    Here are some useful links: security filters, httpsecurity, java config spring security