Skip to content

Commit

Permalink
add csrf whitelist uri and req method
Browse files Browse the repository at this point in the history
  • Loading branch information
JoyChou93 committed May 31, 2019
1 parent dd3792d commit 72a54fa
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
27 changes: 25 additions & 2 deletions src/main/java/org/joychou/WebSecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,39 @@
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.util.matcher.RequestMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Pattern;

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

RequestMatcher csrfRequestMatcher = new RequestMatcher() {

// 配置不需要CSRF校验的请求方式
private Pattern allowedMethods =
Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");

@Override
public boolean matches(HttpServletRequest request) {
// CSRF disabled on allowedMethod
// false表示不校验csrf
return !(allowedMethods.matcher(request.getMethod()).matches());
}

};

@Override
protected void configure(HttpSecurity http) throws Exception {
// http.csrf().disable() // 去掉csrf校验
// 默认token存在session里,现在改为token存在cookie里。但存在后端多台服务器情况,session不能同步的问题,所以一般使用cookie模式。
http.csrf().csrfTokenRepository(new CookieCsrfTokenRepository());
// 默认token存在session里,用CookieCsrfTokenRepository改为token存在cookie里。
// 但存在后端多台服务器情况,session不能同步的问题,所以一般使用cookie模式。
http.csrf()
.requireCsrfProtectionMatcher(csrfRequestMatcher)
.ignoringAntMatchers("/xxe/**", "/fastjon/**") // 不进行csrf校验的uri,多个uri使用逗号分隔
.csrfTokenRepository(new CookieCsrfTokenRepository());
// http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}
}
2 changes: 1 addition & 1 deletion src/main/java/org/joychou/controller/Fastjson.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
@RequestMapping("/fastjson")
public class Fastjson {

@RequestMapping(value = "deserialize", method = {RequestMethod.POST })
@RequestMapping(value = "/deserialize", method = {RequestMethod.POST })
@ResponseBody
public static String Deserialize(@RequestBody String params) {
// 如果Content-Type不设置application/json格式,post数据会被url编码
Expand Down

0 comments on commit 72a54fa

Please sign in to comment.