Vortilion
Vortilion

Reputation: 424

How to use Spring Security .antMatchers() with multiple paths

Is there a difference if I use Spring Securitys "antMatchers()"-method like

.antMatchers(
    "/",
    "/app/**",
    "/profiles/**",
    "/captcha/**",
    c440_START_PAGE,
    FAVICON_ICO,
    C440_LOGIN,
    getCustomerRessourcePath(),
    getCustomerWebRessourcePath(),
    "/services/userService/**",
    "/services/applicationService/**",
    "/services/textContentService/**",
    "/services/textContentBlockService/**",
    "/services/menuItemService/**",
    "/services/calculatorService/**"
).permitAll()

or instead

.antMatchers("/").permitAll()
.antMatchers("/app/**").permitAll()
.antMatchers("/profiles/**").permitAll()
.antMatchers("/captcha/**").permitAll()
.antMatchers(c440_START_PAGE).permitAll()
.antMatchers(FAVICON_ICO).permitAll()
.antMatchers(C440_LOGIN).permitAll()
.antMatchers(getCustomerRessourcePath()).permitAll()
.antMatchers(getCustomerWebRessourcePath()).permitAll()
.antMatchers("/services/userService/**").permitAll()
.antMatchers("/services/applicationService/**").permitAll()
.antMatchers("/services/textContentService/**").permitAll()
.antMatchers("/services/textContentBlockService/**").permitAll()
.antMatchers("/services/menuItemService/**").permitAll()
.antMatchers("/services/calculatorService/**").permitAll()

? I'm new to Spring Security and not sure about this...

Upvotes: 1

Views: 6101

Answers (1)

Madhu Bhat
Madhu Bhat

Reputation: 15183

Both of them are same with your implementation. But the second way provides more flexibility in providing role based authorization etc.

For eg, if you want the role ADMIN to be authorized to access "/" and the role USER to be authorized to access "/app/*", then that would be achieved as below:

.antMatchers("/").hasRole("ADMIN")
.antMatchers("/app/**").hasRole("USER")

Do note that .permitAll() needs to be added only once at the end for every set of patterns with same configuration and not necessarily on every line.

One of the signatures of antMatchers method is

public C antMatchers(java.lang.String... antPatterns)

That means you can pass one or more patterns to the method. More on that can be found on the spring documentation for antMatchers

Upvotes: 3

Related Questions