HTTP状态403 - 未找到预期的CSRF令牌

时间:2015-07-30 12:09:26

标签: java angularjs http spring-mvc spring-security

我正在从角度$ http发布到服务器,我正在

HTTP Status 403 - Expected CSRF token not found. 

我可以找到here一个解决方案是禁用CSRF,但我不确定这是我想要的。请让我知道如何解决这个问题。

我在前端使用Angular JS,在服务器端使用带有Spring安全性3.2的Spring MVC 4。

修改

SecurityConfig.java

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .formLogin()
                .loginPage("/signin")
                .loginProcessingUrl("/signin/authenticate")
                .failureUrl("/signin?param.error=bad_credentials")
            .and()
                .logout()
                    .logoutUrl("/signout")
                    .deleteCookies("JSESSIONID")
            .and()
                .authorizeRequests()
                    .antMatchers("search/**", "/c/**","/admin/**", "/favicon.ico", "/resources/**", "/auth/**", "/signin/**", "/signup/**", "/disconnect/facebook"/*, "/**"*/).permitAll()
                    .antMatchers("/**").authenticated()
            .and()
                .rememberMe()
            .and()
                .apply(
                    new SpringSocialConfigurer());
    }

Angular JS ajax请求:

$http({
        method: 'POST',
        url: 'addCampaign',
        data: JSON.stringify(newCampaign)
    }).
    success(function (data, status, headers, config) {

        //TODO Notification to show the campaign was successfully saved
        $log.info("campaign successfully saved");
    }).error(function (data, status, headers, config) {
        $log.info("campaign could not be saved" + data + " " + status + " " + headers + " " + config);
        //TODO to show notification that the campaign could not be saved succeffsully.
    });

1 个答案:

答案 0 :(得分:1)

我找到了解决这个问题的方法。

我发现spring会将以下两个属性添加到我将返回的JSP视图中

`${_csrf.token}` and `${_csrf.headerName}`

我正在meta

JSP代码中收集这些属性
<meta name="_csrf" content="${_csrf.token}" />

<meta name="_csrf_header" content="${_csrf.headerName}" />

在Javascript中,我编写了以下函数,

function getMetaContentByName(name, content) {
    var content = (content == null) ? 'content' : content;
    return document.querySelector("meta[name='" + name + "']").getAttribute(content);
}

在发送ajax请求时,我包含了存在的CRFS令牌 -

        $http({
            method: 'POST',

            headers: {
                'X-CSRF-TOKEN': getMetaContentByName('_csrf');
            },

            url: requestURL,
            data: data
        }).
        success(function (data, status, headers, config) {

            $log.info("data : " + data);


        })