有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在使用Angular JS的Spring Security登录过程后缺少CSFR_令牌会话属性

我对使用CSRF的AngularJS的Spring Security有问题

我的实现基于以下文档:

http://spring.io/guides/tutorials/spring-security-and-angular-js/

我的问题是,登录/注销过程没有得到正确管理

登录阶段似乎进行得很顺利:响应正常,创建了Java会话,并且有一个属性“SPRING\u SECURITY\u CONTEXT”,其中记录了主体。 但是在登录过程之后,我注意到会话对象中缺少CSFR_令牌的属性

这会产生这样的效果:当我尝试注销时,我会传递带有Spring Security所需的所有头的请求。 但是,org的“doFilterInternal”方法。springframework。安全网状物csrf。CsrfFilter类无法检索属性:

org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository.CSRF_TOKEN

这会导致令牌的重新生成,因为“”令牌丢失“(在会话对象中,而不是在请求头中),所以当“doFilterInternal”进行匹配控制时 在请求中传递令牌后,匹配失败,并在Spring日志中打印:“为…找到了无效的CSRF令牌。”

这个问题会停止过滤器链:在自定义“csrfHeaderFilter”中创建的过滤器不会被调用,因为它是在标准过滤器之后调用的,所以我将此错误页面作为返回:

HTTP状态403-未找到预期的CSRF令牌。你的课程过期了吗

会话未过期。事实上,如果我在浏览器上刷新页面,我可以看到我仍在登录。 在日志中,我可以看到用户名仍然存在,并且在会话中完美地保存了主体对象

如果我在页面刷新后重试注销,注销不会再失败,因为在会话中,属性“CSRF_令牌”现在存在。 注销过程得到了完美的管理,因为在此之后,请求中有一个空会话

怎么了

以下是我的实际安全配置:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, proxyTargetClass = true)
public class SecurityContextConfig extends WebSecurityConfigurerAdapter{

    @Resource(name = "myUserDetailService")
    private UserDetailsService userDetailsService;

    @Bean
    public static StandardPasswordEncoder passwordEncoder() throws Exception {
        return new StandardPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setPasswordEncoder(passwordEncoder());
        provider.setUserDetailsService(userDetailsService);
        auth.authenticationProvider(provider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/main.html","/pages/**").permitAll()
            .anyRequest().authenticated().and()
        .httpBasic()
            .and()
        .csrf()
            .csrfTokenRepository(csrfTokenRepository()).and()
            .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class)
        .logout()
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).permitAll()
            .logoutSuccessUrl("/main.html");
    }

    private Filter csrfHeaderFilter() {
        return new 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);
            }
        };
    }

    private CsrfTokenRepository csrfTokenRepository() {
          HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
          repository.setHeaderName("X-XSRF-TOKEN");
          return repository;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web
            .ignoring()
                .antMatchers("/resources/**");
    }

    @Bean(name="authenticationManager")
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    @Autowired
    public void setObjectPostProcessor(ObjectPostProcessor<Object> objectPostProcessor) {
        super.setObjectPostProcessor(objectPostProcessor);
    }
}

这些是第一次注销尝试时的请求头(不刷新)

HTTP Status 403 - Expected CSRF token not found. Has your session expired?

Request URL:https://localhost:8080/myApp/logout
Request Method:POST
Status Code:403 Forbidden
Remote Address:[::1]:8080

Request Headers
view source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Content-Length:2
Content-Type:application/json;charset=UTF-8
Cookie:JSESSIONID=DFE1A9492F421EDBAEC0DAE6726BFDC4; XSRF-TOKEN=70e2a706-db6d-4f53-b39f-01f6f10b6af1
Host:localhost:8080
Origin:https://localhost:8080
Referer:https://localhost:8080/myApp/main.html
User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36
X-Requested-With:XMLHttpRequest
X-XSRF-TOKEN:70e2a706-db6d-4f53-b39f-01f6f10b6af1

Response Headers
view source
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Language:en
Content-Length:1116
Content-Type:text/html;charset=utf-8
Date:Tue, 19 Apr 2016 12:51:09 GMT
Expires:0
Pragma:no-cache
Server:Apache-Coyote/1.1
Strict-Transport-Security:max-age=31536000 ; includeSubDomains
X-Content-Type-Options:nosniff
X-Frame-Options:DENY
X-XSS-Protection:1; mode=block

共 (1) 个答案

  1. # 1 楼答案

    我自己解决了

    问题是在客户端,我在登录后忽略了对url“user/”的http访问。 如果没有此调用,CSRF_令牌不会在会话中重新保存,从而导致注销过程中服务器端出现问题

    经过此修复后,行为是正确的,并且工作正常

    因此,在Spring AngularJS教程之后,如果esit OK,就会调用url“user”,然后调用url“user/”