Ami*_*mit 6 java spring spring-security csrf-protection
免责声明:我的问题有点类似于这个问题和这个问题,但我已经尝试过在这些主题中提出的所有答案,并且已经花了几天时间来解决这个问题.
我在现有的应用程序(JSP,Servlet)中介绍了Spring Security 3.2.6,我使用的是Java配置.我的应用程序将被浏览器和非浏览器客户端使用.我希望所有对URL(即/webpages/webVersion/和/webpages/webVersion2/)的浏览器请求都启用CSRF,并且所有其他请求都禁用CSRF.非浏览器客户端从不访问上述两个URL,而浏览器应用程序也可以访问CSRF禁用的URL.
我尝试了各种选择:
仅在前面提到的URL上启用Spring Security:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/","/resources/****").permitAll()
.antMatchers("/webpages/webVersion/****", "/webpages/webVersion2/****").authenticated()
.antMatchers("/webpages/****").permitAll()
.anyRequest().anonymous()
.and()
.formLogin().loginPage("/webpages/webVersion/login/newLogin.jsp").failureUrl("/webpages/webVersion/login/newLogin.jsp?error=true").loginProcessingUrl("/j_spring_security_check")
.usernameParameter("username").passwordParameter("password").defaultSuccessUrl("/webpages/webVersion/login/loginSuccess.jsp", true).permitAll()
.and()
.logout().logoutUrl("/webpages/webVersion/logout.jsp").permitAll()
.and().exceptionHandling().accessDeniedPage("/webpages/webVersion/404-error-page.jsp")
.and()
.csrf();
}
Run Code Online (Sandbox Code Playgroud)
这不起作用,因为我观察到所有URL都启用了CSRF.
尝试使用CSRFProtectionMatcher:
.csrf().requireCsrfProtectionMatcher(csrfRequestMatcher);
Run Code Online (Sandbox Code Playgroud)
CSRF仅针对预期的URL启用,但是甚/resources/**至/webpages/**需要在匹配函数内检查URL.考虑到它将适用于所有请求似乎有点多.
尝试使用该configure方法的另一个版本:
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().regexMatchers(".*?/jsp/(?!webVersion|webVersion2).*?");
}
Run Code Online (Sandbox Code Playgroud)
我不确定我是否正确地做到了但这并没有产生我想要的结果.
以上哪种方法是正确的(Spring Security)做我想要的方式?如何从Spring Security配置中实现所需的行为?
事实证明,我的配置存在一些错误,最后我使用方法 3 实现了目标。我使用了以下版本的配置功能以及常用功能configure(HttpSecurity http)。
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().regexMatchers(".*?/jsp/(?!webVersion|webVersion2).*?");
}
Run Code Online (Sandbox Code Playgroud)