在我的
Spring Boot / AngularJS应用程序中,我有以下CSRF配置:
@Override protected void configure(final HttpSecurity http) throws Exception { http.csrf().csrfTokenRepository(csrfTokenRepository()); http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); final String[] restEndpointsToSecure = WebSecurityConfig.restEndpointsToSecure; for (final String endpoint : restEndpointsToSecure) { http.authorizeRequests().antMatchers("/" + endpoint + "/**").hasRole(UserRoleEnum.USER.toString()); } http.addFilterAfter(csrfTokenResponseHeaderBindingFilter(),CsrfFilter.class); xAuthTokenConfigurer.setDetailsService(userDetailsServiceBean()); final SecurityConfigurer<DefaultSecurityFilterChain,HttpSecurity> securityConfigurerAdapter = xAuthTokenConfigurer; http.apply(securityConfigurerAdapter); }
CSRF-令牌过滤器如下所示:
@Override protected void doFilterInternal(HttpServletRequest request,HttpServletResponse response,javax.servlet.FilterChain filterChain) throws ServletException,IOException { final CsrfToken csrf = (CsrfToken)request.getAttribute(CsrfToken.class.getName()); if (csrf != null) { Cookie cookie = WebUtils.getCookie(request,"XSRF-TOKEN"); final 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); }
通常它工作正常,请求头属性X-XSRF-TOKEN与每个请求一起发送.但我有一个奇怪的行为.
我将在应用程序中更新我的用户配置文件.它第一次工作正常,第二次,我得到一个HTTP 403 Forbidden,实际上我真的不知道为什么.
我在这两个更新之间没有做任何事情(没有导航到这两个更新之间的其他页面或其他内容).
在底部的图片中,左边的Request是有效的,右边是failes.唯一不同的是,在右侧,响应头中缺少属性Set-Cookie和X-Application-context.请求标头是相同的.
有谁知道我在这里做错了什么.这对我来说是神秘主义者.
解决方法
好像前端userProfile.controller中可能存在一些功能错误
Your Cookie SessionID redirected form the request header is getting same in the response header which results in INVALID_SESSIONID hence the user is redirected to the login page or your signup page
作为解决方案,您可以更正前端控制器或作为另一种解决方法,您可以将以下内容添加到您的代码中
>仅在检测到CORS时添加CORS标头并传递原始标头,以便允许访问用户内容.
>使用http 200消息响应OPTIONS请求
static final String ORIGIN = "Origin"; if (request.getHeader(ORIGIN).equals("null")) { String origin = request.getHeader(ORIGIN); response.setHeader("Access-Control-Allow-Origin","*");//* or origin as u prefer response.setHeader("Access-Control-Allow-Credentials","true"); response.setHeader("Access-Control-Allow-Headers",request.getHeader("Access-Control-Request-Headers")); } if (request.getMethod().equals("OPTIONS")) { try { response.getWriter().print("OK"); response.getWriter().flush(); } catch (IOException e) { e.printStackTrace(); } }
//your other configs < security:custom-filter ref="corsHandler" after="PRE_AUTH_FILTER"/>