如何将CSRF令牌从AngularJS前端发送到Spring REST服务后端? [英] How do I send CSRF tokens from AngularJS front end to Spring REST service backend?

查看:33
本文介绍了如何将CSRF令牌从AngularJS前端发送到Spring REST服务后端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在AngularJS前端和Spring Boot REST后端之间设置CSRF保护?让我们使用 http.post("/send-pin",JSONobject)..调用下面的代码作为示例.

How do I set up CSRF protection between an AngularJS front end and a Spring Boot REST backend? Let's take the http.post("/send-pin", JSONobject)... call from the code below as an example.

当我尝试使用 http从AngularJS前端方法以/send-pin url模式调用Spring Boot REST服务时,服务器日志中出现以下错误.post("/send-pin",JSONobject)... :

I am getting the following error in the server logs when I try to call a Spring Boot REST service at the /send-pin url pattern from an AngularJS front end method using http.post("/send-pin", JSONobject)...:

Invalid CSRF token found for http://localhost:9000/send-pin

我阅读了其他帖子,表示需要在发出请求的AngularJS代码中设置csrf令牌,但链接中的代码使用语法 $(document).ajaxSend(function(e,xhr,options){xhr.setRequestHeader('X-CSRF-TOKEN',token);}); ,它不会直接粘贴到下面的我的代码中.另外,链接中的clode从表单获取数据,而我的代码从AngularJS控制器获取数据.需要对以下代码进行哪些具体更改,以便后端REST服务成功处理AngularJS应用对运行在 localhost:9000/send-pin 网址?

I read this other posting, which states that the csrf token needs to be set in the AngularJS code that makes the request, but the code in the link uses the syntax $(document).ajaxSend(function(e, xhr, options) {xhr.setRequestHeader('X-CSRF-TOKEN', token);});, which does not directly paste into my code below. Also, the clode in the link takes data from a form, while my code takes data from an AngularJS controller. What specific changes need to be made to the code below so that the backend REST service will successfully process the request made by the AngularJS app to the REST service running at the localhost:9000/send-pin url?

这是AngularJS中的方法:

Here is the method in AngularJS:

$scope.login = function() {
    auth.authenticate1($scope.credentials, function(authenticated1) {
        if (authenticated1) {//authenticated1 returns true
            var resultmessage = { "name": $scope.credentials.username };
            $http.post('/send-pin', resultmessage).then(function(response) {//this call triggers the Invalid CSRF token error shown above
                $scope.processStep = response.data.content;
                auth.usrname = response.data.name;
            });
            $scope.error = false;
        } else {
            $scope.error = true;
        }
    })
}

这是设置SpringSecurity配置的UiApplication.java类:

Here is the UiApplication.java class that sets the SpringSecurity configuration:

@SpringBootApplication
@Controller
@EnableJpaRepositories(basePackages = "demo", considerNestedRepositories = true)
public class UiApplication extends WebMvcConfigurerAdapter {

    // Match everything without a suffix (so not a static resource)
    @RequestMapping(value = "/{[path:[^\\.]*}")
    public String redirect() {
        // Forward to home page so that route is preserved.
        return "forward:/";
    }

    @RequestMapping("/user")
    @ResponseBody
    public Principal user(HttpSession session, Principal user) {
        return user;
    }

    public static void main(String[] args) {
        SpringApplication.run(UiApplication.class, args);
    }

    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver slr = new SessionLocaleResolver();
        slr.setDefaultLocale(Locale.US);
        return slr;
    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        lci.setParamName("lang");
        return lci;
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("login");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }

    @Order(Ordered.HIGHEST_PRECEDENCE)
    @Configuration
    protected static class AuthenticationSecurity extends GlobalAuthenticationConfigurerAdapter {

        @Autowired
        private Users users;

        @Override
        public void init(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(users);
        }
    }

    @SuppressWarnings("deprecation")
    @Configuration
    @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
    @EnableWebMvcSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    protected static class SecurityConfiguration extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.httpBasic().and().authorizeRequests()
                .antMatchers("/check-pin").permitAll()
                .antMatchers("/index.html", "/", "/login", "/someotherrurl") 
                .permitAll().anyRequest().authenticated().and().csrf()
                .csrfTokenRepository(csrfTokenRepository()).and()
                .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);
        }

        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;
        }
    }   
}

这是Linux终端上的错误日志,该日志在REST服务运行时打印出来:

Here is the error log from the Linux terminal which prints out while the REST service is running:

2016-01-15 13:15:27.704 DEBUG 7031 --- [nio-9000-exec-1] tRepository$SaveToSessionResponseWrapper : Skip invoking on
2016-01-15 13:15:27.704 DEBUG 7031 --- [nio-9000-exec-1] tRepository$SaveToSessionResponseWrapper : Skip invoking on
2016-01-15 13:15:27.704 DEBUG 7031 --- [nio-9000-exec-1] o.s.s.w.a.ExceptionTranslationFilter     : Chain processed normally
2016-01-15 13:15:27.704 DEBUG 7031 --- [nio-9000-exec-1] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
2016-01-15 13:15:27.713 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/css/**'
2016-01-15 13:15:27.713 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/js/**'
2016-01-15 13:15:27.713 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/images/**'
2016-01-15 13:15:27.713 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/**/favicon.ico'
2016-01-15 13:15:27.713 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/error'
2016-01-15 13:15:27.713 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/autoconfig']
2016-01-15 13:15:27.713 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/autoconfig'
2016-01-15 13:15:27.713 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/autoconfig/**']
2016-01-15 13:15:27.713 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/autoconfig/**'
2016-01-15 13:15:27.713 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/autoconfig.*']
2016-01-15 13:15:27.713 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/autoconfig.*'
2016-01-15 13:15:27.713 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/autoconfig/']
2016-01-15 13:15:27.713 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/autoconfig/'
2016-01-15 13:15:27.713 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/metrics']
2016-01-15 13:15:27.713 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/metrics'
2016-01-15 13:15:27.713 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/metrics/**']
2016-01-15 13:15:27.713 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/metrics/**'
2016-01-15 13:15:27.713 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/metrics.*']
2016-01-15 13:15:27.713 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/metrics.*'
2016-01-15 13:15:27.713 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/metrics/']
2016-01-15 13:15:27.713 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/metrics/'
2016-01-15 13:15:27.713 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/trace']
2016-01-15 13:15:27.713 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/trace'
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/trace/**']
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/trace/**'
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/trace.*']
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/trace.*'
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/trace/']
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/trace/'
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/env']
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/env'
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/env/**']
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/env/**'
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/env.*']
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/env.*'
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/env/']
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/env/'
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/health']
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/health'
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/health/']
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/health/'
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/mappings']
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/mappings'
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/mappings/**']
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/mappings/**'
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/mappings.*']
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/mappings.*'
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/mappings/']
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/mappings/'
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/dump']
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/dump'
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/dump/**']
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/dump/**'
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/dump.*']
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/dump.*'
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/dump/']
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/dump/'
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/error']
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/error'
2016-01-15 13:15:27.714 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/error/']
2016-01-15 13:15:27.715 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/error/'
2016-01-15 13:15:27.715 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/beans']
2016-01-15 13:15:27.716 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/beans'
2016-01-15 13:15:27.716 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/beans/**']
2016-01-15 13:15:27.716 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/beans/**'
2016-01-15 13:15:27.717 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/beans.*']
2016-01-15 13:15:27.717 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/beans.*'
2016-01-15 13:15:27.717 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/beans/']
2016-01-15 13:15:27.717 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/beans/'
2016-01-15 13:15:27.717 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/info']
2016-01-15 13:15:27.717 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/info'
2016-01-15 13:15:27.717 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/info/']
2016-01-15 13:15:27.717 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/info/'
2016-01-15 13:15:27.717 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/configprops']
2016-01-15 13:15:27.717 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/configprops'
2016-01-15 13:15:27.717 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/configprops/**']
2016-01-15 13:15:27.717 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/configprops/**'
2016-01-15 13:15:27.717 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/configprops.*']
2016-01-15 13:15:27.717 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/configprops.*'
2016-01-15 13:15:27.717 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/configprops/']
2016-01-15 13:15:27.717 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/send-pin'; against '/configprops/'
2016-01-15 13:15:27.717 DEBUG 7031 --- [io-9000-exec-10] o.s.s.web.util.matcher.OrRequestMatcher  : No matches found
2016-01-15 13:15:27.717 DEBUG 7031 --- [io-9000-exec-10] o.s.security.web.FilterChainProxy        : /send-pin at position 1 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2016-01-15 13:15:27.717 DEBUG 7031 --- [io-9000-exec-10] o.s.security.web.FilterChainProxy        : /send-pin at position 2 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2016-01-15 13:15:27.717 DEBUG 7031 --- [io-9000-exec-10] w.c.HttpSessionSecurityContextRepository : Obtained a valid SecurityContext from SPRING_SECURITY_CONTEXT: 'org.springframework.security.core.context.SecurityContextImpl@d8393cb4: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@d8393cb4: Principal: org.springframework.security.core.userdetails.User@63d9948c: Username: another@shirt.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffdaa08: RemoteIpAddress: 127.0.0.1; SessionId: 61483B5DDC3336EC44BF528C97749AA9; Granted Authorities: ROLE_USER'
2016-01-15 13:15:27.717 DEBUG 7031 --- [io-9000-exec-10] o.s.security.web.FilterChainProxy        : /send-pin at position 3 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2016-01-15 13:15:27.717 DEBUG 7031 --- [io-9000-exec-10] o.s.s.w.header.writers.HstsHeaderWriter  : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@4f81666
2016-01-15 13:15:27.723 DEBUG 7031 --- [io-9000-exec-10] o.s.security.web.FilterChainProxy        : /send-pin at position 4 of 12 in additional filter chain; firing Filter: 'CsrfFilter'
2016-01-15 13:15:27.724 DEBUG 7031 --- [io-9000-exec-10] o.s.security.web.csrf.CsrfFilter         : Invalid CSRF token found for http://localhost:9000/send-pin
2016-01-15 13:15:27.725 DEBUG 7031 --- [io-9000-exec-10] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed

推荐答案

注意:我是OP,这个答案实际上是解决问题的方法.

要解决此问题,需要在 SecurityConfiguration 类中添加以下行:

The solution to this required adding the following line to the SecurityConfiguration class:

.antMatchers("/send-pin").permitAll()  

此更改导致SecurityConfiguration.configure(...)方法现在看起来像:

This change caused SecurityConfiguration.configure(...) method to now look like:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic().and().authorizeRequests()
            .antMatchers("/send-pin").permitAll() 
            .antMatchers("/check-pin").permitAll()
            .antMatchers("/index.html", "/", "/login", "/someotherrurl") 
            .permitAll().anyRequest().authenticated().and().csrf()
            .csrfTokenRepository(csrfTokenRepository()).and()
            .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);
    }  

请注意,从OP版本开始只有一行更改.这是一个非常简单的答案.由于它是如此明显,几乎感到羞耻,但我将其发布是为了帮助将来遇到类似问题的其他人.

Notice the one line change from the OP version. This is a very simple answer. Almost ashamed to post it because it is so obvious, but I am posting it to help others who face a similar problem in the future.

在尝试@charlieti的建议以检查Firefox调试工具的网络"选项卡后,发现了以下两个cookie,并随请求发送: JSESSIONID:"99192501E7CEA0EDEF853BD666AF3C35" XSRF-TOKEN:"b50afb87-e15c-4bef-93ca-7c2fdf145fd8" ,即使同一请求的服务器日志仍归结为为http://localhost:9000/找到的无效CSRF令牌发送图钉.这使我检查了为什么拒绝发送的令牌,几分钟后,我注意到url模式缺少 antmatchers(...),从而导致了此问题.

I found this after trying @charlieti's suggestion to examine the Network tab of the Firefox debug tools, which showed that the following two cookies were sent with the request: JSESSIONID:"99192501E7CEA0EDEF853BD666AF3C35" and XSRF-TOKEN:"b50afb87-e15c-4bef-93ca-7c2fdf145fd8", even though the server log for the same request still boiled down to Invalid CSRF token found for http://localhost:9000/send-pin . This caused me to examine why the sent token was being rejected, and a few minutes later I noticed the missing antmatchers(...) for the url pattern, leading to this answer.

这篇关于如何将CSRF令牌从AngularJS前端发送到Spring REST服务后端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆