See Spring Security Reference:
Our examples have only required users to be authenticated and have done so for every URL in our application. We can specify custom requirements for our URLs by adding multiple children to our
http.authorizeRequests()
method. For example:protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/resources/**", "/signup", "/about").permitAll() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')") .anyRequest().authenticated() .and() // ... .formLogin(); }
1 There are multiple children to the
http.authorizeRequests()
method each matcher is considered in the order they were declared.2
We specified multiple URL patterns that any user can access. Specifically, any user can access a request if the URL starts with “/resources/”, equals “/signup”, or equals “/about”.3
Any URL that starts with “/admin/” will be resticted to users who have the role “ROLE_ADMIN”. You will notice that since we are invoking the hasRole method we do not need to specify the “ROLE_” prefix.4
Any URL that starts with “/db/” requires the user to have both “ROLE_ADMIN” and “ROLE_DBA”. You will notice that since we are using the hasRole expression we do not need to specify the “ROLE_” prefix.5
Any URL that has not already been matched on only requires that the user be authenticated
Your second use of .authorizeRequests()
overrides the first one.
Also see AntPathMatcher:
The mapping matches URLs using the following rules:
?
matches one character
*
matches zero or more characters
**
matches zero or more directories in a pathExamples
com/t?st.jsp
— matchescom/test.jsp
but alsocom/tast.jsp
orcom/txst.jsp
com/*.jsp
— matches all.jsp
files in thecom
directory
com/**/test.jsp
— matches alltest.jsp
files underneath thecom
path
org/springframework/**/*.jsp
— matches all.jsp
files underneath theorg/springframework
path
org/**/servlet/bla.jsp
— matchesorg/springframework/servlet/bla.jsp
but alsoorg/springframework/testing/servlet/bla.jsp
andorg/servlet/bla.jsp
Your modified code:
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/rest/open/**").permitAll()
.antMatchers("/login/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.defaultSuccessUrl("/dashboard")
.loginProcessingUrl("/j_spring_security_check")
.usernameParameter("username")
.passwordParameter("password")
.and()
.logout()
.logoutUrl("/j_spring_security_logout")
.logoutSuccessUrl("/login?logout")
.and()
.csrf();
}