我在Spring Security中使用Angularjs。当我将注册表发送到服务器时,我收到403禁止错误。我添加了
.csrf().csrfTokenRepository(csrfTokenRepository());
配置我的配置(HttpSecurity http)方法。
我添加了
$httpProvider.defaults.withCredentials = true;
$httpProvider.interceptors.push('XSRFInterceptor');
$httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
到我的角度模块的配置方法。
我试图遵循Spring Angular教程,但它不适合我。
Spring安全设置
@Override
protected void configure(HttpSecurity http) throws Exception{
http
.httpBasic().and()
.authorizeRequests()
.antMatchers("/api/todos").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.usernameParameter("email")
.passwordParameter("password")
.permitAll()
.and()
.csrf().csrfTokenRepository(csrfTokenRepository());
}
private CsrfTokenRepository csrfTokenRepository() {
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
repository.setHeaderName("X-XSRF-TOKEN");
return repository;
}
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);
}
Angularjs
var todoApp = angular.module('todoApp', [
'ngCookies',
'ui.router',
'jcs-autoValidate',
'angular-ladda'
]);
todoApp.config(function ($stateProvider, $urlRouterProvider, $httpProvider) {
$httpProvider.defaults.withCredentials = true;
$httpProvider.interceptors.push('XSRFInterceptor');
$httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
});
用户服务
create: function(userData, callback) {
$http.post('/api/users', userData).then(function (res) {
return callback(res.data);
}, 'error')
},
我将此工厂添加到我的项目中,它来自这个问题:HTTP Status 403 - Invalid CSRF Token 'null' was found on the request parameter
todoApp.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;
});
我对此代码的理解是,它将CSRF令牌添加到标头中。但事实并非如此。任何帮助都会很棒。