Bram Luyten
Bram Luyten

Reputation: 1063

Explicitly secure a specific pattern instead of ignoring all non-secured patterns

I have an application where I only need to secure /admin/ pages. All of the other pages have no login, account or other features that require security.

According to other questions and tutorials, I have currently implemented this with explicitly ignoring all paths that don't require security, e.g.

        web
                .ignoring()
                .antMatchers("/js/**");

        web
                .ignoring()
                .antMatchers("/static/**");

        web
                .ignoring()
                .antMatchers("/images/**");

        web
                .ignoring()
                .antMatchers("/css/**");

        web
                .ignoring()
                .antMatchers("/fonts/**");

This makes the configuration larger and not entirely clear on what you're exactly securing, since it only states the exceptions.

Is there a way to first explicitly disable all security, and then add the patterns for which you want to activate it?

Upvotes: 0

Views: 1767

Answers (1)

Rob Winch
Rob Winch

Reputation: 21720

Ignoring security (even for public static URLs) is generally considered bad practice unless you have explicit reasons to do so. Remember Spring Security also helps with things like Security HTTP Response Headers to ensure your application is secured.

With that in mind, would remove the ignoring configuration you have and simply update your security authorization rules. For example:

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/admin/").hasRole("ADMIN")
                .and()
            .formLogin()
                ...
    }

    // ...
}

That said if you really need to ignore all requests except those that start with admin, you can easily perform this with a regular expression:

web
    .ignoring()
        .regexMatchers("^(?!/admin/).*");

You can also inject custom matcher implementations. Spring Security even provides the ones below out of the box:

RequestMatcher adminRequests = new AntPathRequestMatcher("/admin/**");
RequestMatcher notAdminRequests = new NegatedRequestMatcher(adminRequests);
web
    .ignoring()
        .requestMatchers(notAdminRequests);

Upvotes: 2

Related Questions