繁体   English   中英

Spring Security + AngularJS:POST请求

[英]Spring Security + AngularJS: POST request

我有一个Web应用程序,后面使用Java Spring,前面使用AngularJS。

春季安全配置(Java配置)

@Override
protected void configure(HttpSecurity http) throws Exception {
        http
        .authenticationProvider(authenticationProvider())
        .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint)
        .and()
        .formLogin().loginProcessingUrl("loginProcessingUrl")
                    .successHandler(authSuccessHandler)
                    .failureHandler(authFailureHandler)
                    .usernameParameter("username")
                    .passwordParameter("password")
        .and()
        .logout().permitAll().logoutSuccessHandler(logoutSuccessHandler)
        .and()
        .authorizeRequests().antMatchers("/demo/**","/postTest/**").permitAll()
        .anyRequest().authenticated()
        .and()
        .httpBasic()
        .and()
        .csrf().csrfTokenRepository(csrfTokenRepository())
        .and()
        .addFilterAfter(new CsrfCustomFilter(), CsrfFilter.class);
    }

CSRF滤镜

public class CsrfCustomFilter 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);
}
}

来自AngularJS的POST请求

$http({method:'POST',data:"celine",url:"http://localhost:8080/postTest",cache:true})
        .success(function(data) {
          console.log("success POST");
        })
        .error(function(data, status, headers, config, statusText) {
          console.log("status: " + status + " statusText: " + statusText);
        });

- 更新 -
我可以使用从前到后的GET请求,但POST请求似乎无效。 我在正面收到403 Forbidden错误(在我的日志中:“状态:403 statusText:未定义”)。

对于POST请求,我可以正确地将XSRF-TOKEN发送给Spring,但是Spring返回403 Forbidden 所以我想问题出在我的Spring Security配置而不是Angular。

我的POST请求标头 在此处输入图片说明

感谢您的时间。

我对跨域请求有类似的问题,因为AngularJS不在跨域请求中发送XSRF标头。 (在此页面上搜索“将不会为跨域请求设置标题”)。

编写此$http拦截器

angular.module('appBoot')
  .factory('XSRFInterceptor', function ($cookies, $log) {

    var XSRFInterceptor = {

      request: function(config) {

        var token = $cookies.get('XSRF-TOKEN');

        if (token) {
          config.headers['X-XSRF-TOKEN'] = token;
          $log.info("X-XSRF-TOKEN: " + token);
        }

        return config;
      }
    };
    return XSRFInterceptor;
  });

并像这样配置

angular.module('appBoot', ['ngCookies', 'ngMessages', 'ui.bootstrap', 'vcRecaptcha'])
    .config(['$httpProvider', function ($httpProvider) {

      $httpProvider.defaults.withCredentials = true;
      $httpProvider.interceptors.push('XSRFInterceptor');

    }]);

解决了我的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM