See Spring安全参考 http://docs.spring.io/spring-security/site/docs/4.1.2.RELEASE/reference/htmlsingle/#authorize-requests:
我们的示例仅要求用户进行身份验证,并且对应用程序中的每个 URL 都进行了身份验证。我们可以通过向 URL 添加多个子项来指定 URL 的自定义要求http.authorizeRequests()
方法。例如:
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 有多个孩子http.authorizeRequests()
方法 每个匹配器按照声明的顺序进行考虑。
2
我们指定了任何用户都可以访问的多个 URL 模式。具体来说,如果 URL 以“/resources/”开头、等于“/signup”或等于“/about”,则任何用户都可以访问请求。
3
任何以“/admin/”开头的 URL 将仅限于具有“ROLE_ADMIN”角色的用户。您会注意到,由于我们正在调用 hasRole 方法,因此不需要指定“ROLE_”前缀。
4
任何以“/db/”开头的 URL 都要求用户同时拥有“ROLE_ADMIN”和“ROLE_DBA”。您会注意到,由于我们使用的是 hasRole 表达式,因此不需要指定“ROLE_”前缀。
5
任何尚未匹配的 URL 仅需要对用户进行身份验证
您的第二次使用.authorizeRequests()
覆盖第一个。
另请参阅蚂蚁路径匹配器 http://docs.spring.io/autorepo/docs/spring-framework/4.2.1.RELEASE/javadoc-api/org/springframework/util/AntPathMatcher.html:
映射使用以下规则匹配 URL:
?
匹配一个字符
*
匹配零个或多个字符
**
匹配路径中的零个或多个目录
Examples
com/t?st.jsp
- 火柴com/test.jsp
但是也com/tast.jsp
or com/txst.jsp
com/*.jsp
— 匹配所有.jsp
文件在com
目录
com/**/test.jsp
— 匹配所有test.jsp
下面的文件com
path
org/springframework/**/*.jsp
— 匹配所有.jsp
下面的文件org/springframework
path
org/**/servlet/bla.jsp
- 火柴org/springframework/servlet/bla.jsp
但是也org/springframework/testing/servlet/bla.jsp
and org/servlet/bla.jsp
您修改后的代码:
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();
}