Renaming Spring csrf token variable

前端 未结 2 1700
南方客
南方客 2021-01-16 13:35

My application runs under another portal application. Both are implemented in spring and both use csrf security.

My need is basically change how the csrf token is n

相关标签:
2条回答
  • 2021-01-16 13:53

    Please remember to delete any old cookies that you've got before renaming the Header. I had the same problem where everything was setup nicely, but old cookies in the browser caused the filter function to be useless basically.

    0 讨论(0)
  • 2021-01-16 14:02

    This is what worked for me:-

    @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;
    }
    
    }
    

    And the filter:-

    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);
        }
    }
    

    Did you override the WebSecurityConfigurerAdapter#configure method?

    0 讨论(0)
提交回复
热议问题