重命名Spring CSRF令牌变量 [英] Renaming Spring csrf token variable
问题描述
我的应用程序在另一个门户网站应用程序下运行.两者都在spring中实现,并且都使用csrf安全性.
My application runs under another portal application. Both are implemented in spring and both use csrf security.
我的需求是基本上更改会话中csrf令牌的命名方式,以便两个令牌都可以正常工作.到目前为止,我尝试创建另一个令牌存储库,并尝试在安全性配置类中更改参数名称和会话属性名称.
My need is basically change how the csrf token is named in the session, so both the tokens can work without conflicts. What I tried so far is creating another token repository and trying to change the parameter name and the session attribute name in the security config class.
final HttpSessionCsrfTokenRepository tokenRepository = new HttpSessionCsrfTokenRepository();
tokenRepository.setHeaderName("TOOLBIZ-CSRF-TOKEN");
tokenRepository.setParameterName("toolbiz_csfr");
//tokenRepository.setSessionAttributeName("toolbiz_csrf");
当我发出请求时,Spring并不是非常喜欢这种新设置,并且日志会生成以下行:
When I make request Spring doesn't really like this new setup very much, and the log produces the following line:
Invalid CSRF token found
我该怎么办?我想念什么吗?
What should I do more? Am I missing something?
推荐答案
这对我有用:-
@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class OptosoftWebfrontSecurity extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/assets/**").permitAll()
.anyRequest().authenticated().and().formLogin().and()
.httpBasic().disable()
.addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class)
.csrf().csrfTokenRepository(csrfTokenRepository());
}
private CsrfTokenRepository csrfTokenRepository() {
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
repository.setHeaderName("X-XSRF-TOKEN");
repository.setParameterName("_csrf");
return repository;
}
}
和过滤器:-
public class CsrfHeaderFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class
.getName());
if (csrf != null) {
Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
String token = csrf.getToken();
if (cookie == null || token != null
&& !token.equals(cookie.getValue())) {
cookie = new Cookie("XSRF-TOKEN", token);
cookie.setPath("/");
response.addCookie(cookie);
}
}
filterChain.doFilter(request, response);
}
}
您是否重写了WebSecurityConfigurerAdapter#configure方法?
Did you override the WebSecurityConfigurerAdapter#configure method?
这篇关于重命名Spring CSRF令牌变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!