Multiple antMatchers in Spring security

SpringSpring MvcSpring Security

Spring Problem Overview


I work on content management system, that has five antMatchers like the following:

http.authorizeRequests()
		.antMatchers("/", "/*.html").permitAll()
		.antMatchers("/user/**").hasRole("USER")
		.antMatchers("/admin/**").hasRole("ADMIN")
		.antMatchers("/admin/login").permitAll()
		.antMatchers("/user/login").permitAll()
		.anyRequest().authenticated()
		.and()
    	.csrf().disable();

which suppose to mean that the visitors can see all site at root path (/*), and users can see only (/user), admin can see only (/admin), and there are two login pages one for users and another for admin.

The code seems to work fine, except the admin section - it doesn't work but return access denied exception.

Spring Solutions


Solution 1 - Spring

I believe that the problem is in the order of your rules:

.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/admin/login").permitAll()

The order of the rules matters and the more specific rules should go first. Now everything that starts with /admin will require authenticated user with ADMIN role, even the /admin/login path (because /admin/login is already matched by the /admin/** rule and therefore the second rule is ignored).

The rule for the login page should therefore go before the /admin/** rule. E.G.

.antMatchers("/admin/login").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBashar AbutariehView Question on Stackoverflow
Solution 1 - SpringBohuslav BurghardtView Answer on Stackoverflow