Angular 6 Spring Boot POST问题

11

我正在尝试建立一个Angular 6应用程序,它与本地Spring Boot REST应用程序通信。

我终于能够登录并使用GET请求,这些请求似乎使用正确的cookie。有2个cookie,一个是JSESSION cookie,另一个是XSRF cookie。问题在于,我从任何POST请求中获得403响应。我相当有信心这更多是我的Spring设置的问题。

Spring安全配置:

@Configuration
public class CORSConfig implements WebMvcConfigurer {

@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
        .allowedOrigins("http://localhost:4200")
        .allowCredentials(true)
        .allowedHeaders("*")
        .allowedMethods("GET", "POST", "*")
        .exposedHeaders("Set-Cookie","Authorization");
}

并且
@Override
protected void configure(HttpSecurity http) throws Exception {
     http
        .cors()
     .and()
        .httpBasic()
     .and()
        .authorizeRequests()
          .antMatchers("/", "/main", "/user", "/runtime.js","/polyfills.js",
                  "/main.js", "/styles.js", "/vendor.js").permitAll()
          .anyRequest().authenticated()
     .and()
        .csrf()

.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
     .and().sessionManagement().maximumSessions(1).and()
          .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);

}

请注意,除了“/user”之外的antMatchers在此设置中实际上并未被使用。这些文件是使用ng serve本地提供服务的。
我的Angular设置:
@Injectable()
export class AuthenticationInterceptor implements HttpInterceptor{

intercept(req: HttpRequest<any>, next: HttpHandler): 
Observable<HttpEvent<any>>
{
    const xhr = req.clone({
        headers: req.headers.set('X-Requested-With', 'XMLHttpRequest'),
        withCredentials: true
      });
      return next.handle(xhr);
}

这个调用现在可以正常运行:
getExercise(id:Number): Observable<Exercise>
{
    return this.http.get<Exercise>(environment.baseUrl + '/api/exercise/' + id);
}

但这个请求是POST类型的,不会执行。
saveExercise(exercise: Exercise): Observable<Exercise>
{
   return this.http.post<Exercise>(environment.baseUrl + 
   '/newExercise',exercise);
}

Spring Security记录GET请求的日志:

DEBUG 18776 --- [nio-8080-exec-1] o.s.b.w.s.f.OrderedRequestContextFilter  : Bound request context to thread: org.apache.catalina.connector.RequestFacade@29dbd699
DEBUG 18776 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /api/exercise/2 at position 1 of 14 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
DEBUG 18776 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /api/exercise/2 at position 2 of 14 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
DEBUG 18776 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : No HttpSession currently exists
DEBUG 18776 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: null. A new one will be created.
DEBUG 18776 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /api/exercise/2 at position 3 of 14 in additional filter chain; firing Filter: 'HeaderWriterFilter'
DEBUG 18776 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /api/exercise/2 at position 4 of 14 in additional filter chain; firing Filter: 'CorsFilter'
DEBUG 18776 --- [nio-8080-exec-1] 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@2de4577a
DEBUG 18776 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
DEBUG 18776 --- [nio-8080-exec-1] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
DEBUG 18776 --- [nio-8080-exec-1] o.s.b.w.s.f.OrderedRequestContextFilter  : Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade@29dbd699
DEBUG 18776 --- [nio-8080-exec-4] o.s.b.w.s.f.OrderedRequestContextFilter  : Bound request context to thread: org.apache.catalina.connector.RequestFacade@29dbd699
DEBUG 18776 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy        : /api/exercise/2 at position 1 of 14 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
DEBUG 18776 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy        : /api/exercise/2 at position 2 of 14 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
DEBUG 18776 --- [nio-8080-exec-4] w.c.HttpSessionSecurityContextRepository : Obtained a valid SecurityContext from SPRING_SECURITY_CONTEXT: 'org.springframework.security.core.context.SecurityContextImpl@84a2a85a: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@84a2a85a: Principal: com.op.movement.model.ApplicationUserDetails@7b5de4fa; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Not granted any authorities'
DEBUG 18776 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy        : /api/exercise/2 at position 3 of 14 in additional filter chain; firing Filter: 'HeaderWriterFilter'
DEBUG 18776 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy        : /api/exercise/2 at position 4 of 14 in additional filter chain; firing Filter: 'CorsFilter'
DEBUG 18776 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy        : /api/exercise/2 at position 5 of 14 in additional filter chain; firing Filter: 'CsrfFilter'
DEBUG 18776 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy        : /api/exercise/2 at position 6 of 14 in additional filter chain; firing Filter: 'LogoutFilter'
DEBUG 18776 --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'GET /api/exercise/2' doesn't match 'POST /logout
DEBUG 18776 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy        : /api/exercise/2 at position 7 of 14 in additional filter chain; firing Filter: 'ConcurrentSessionFilter'
DEBUG 18776 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy        : /api/exercise/2 at position 8 of 14 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
DEBUG 18776 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy        : /api/exercise/2 at position 9 of 14 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
DEBUG 18776 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy        : /api/exercise/2 at position 10 of 14 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
DEBUG 18776 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy        : /api/exercise/2 at position 11 of 14 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
DEBUG 18776 --- [nio-8080-exec-4] o.s.s.w.a.AnonymousAuthenticationFilter  : SecurityContextHolder not populated with anonymous token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken@84a2a85a: Principal: com.op.movement.model.ApplicationUserDetails@7b5de4fa; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Not granted any authorities'
DEBUG 18776 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy        : /api/exercise/2 at position 12 of 14 in additional filter chain; firing Filter: 'SessionManagementFilter'
DEBUG 18776 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy        : /api/exercise/2 at position 13 of 14 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
DEBUG 18776 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy        : /api/exercise/2 at position 14 of 14 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
DEBUG 18776 --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/api/exercise/2'; against '/'
DEBUG 18776 --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/api/exercise/2'; against '/main'
DEBUG 18776 --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/api/exercise/2'; against '/user'
DEBUG 18776 --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/api/exercise/2'; against '/runtime.js'
DEBUG 18776 --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/api/exercise/2'; against '/polyfills.js'
DEBUG 18776 --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/api/exercise/2'; against '/main.js'
DEBUG 18776 --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/api/exercise/2'; against '/styles.js'
DEBUG 18776 --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/api/exercise/2'; against '/vendor.js'
DEBUG 18776 --- [nio-8080-exec-4] o.s.s.w.a.i.FilterSecurityInterceptor    : Secure object: FilterInvocation: URL: /api/exercise/2; Attributes: [authenticated]
DEBUG 18776 --- [nio-8080-exec-4] o.s.s.w.a.i.FilterSecurityInterceptor    : Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@84a2a85a: Principal: com.op.movement.model.ApplicationUserDetails@7b5de4fa; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Not granted any authorities
DEBUG 18776 --- [nio-8080-exec-4] o.s.s.access.vote.AffirmativeBased       : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@74ead523, returned: 1
 DEBUG 18776 --- [nio-8080-exec-4] o.s.s.w.a.i.FilterSecurityInterceptor    : Authorization successful
DEBUG 18776 --- [nio-8080-exec-4] o.s.s.w.a.i.FilterSecurityInterceptor    : RunAsManager did not change Authentication object
DEBUG 18776 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy        : /api/exercise/2 reached end of additional filter chain; proceeding with original chain
Getting exercise by ID: 2
DEBUG 18776 --- [nio-8080-exec-4] org.hibernate.SQL                        : select exercise0_.id as id1_0_0_, exercise0_.instructions as instruct2_0_0_, exercise0_.name as name3_0_0_ from operation_movement.exercises exercise0_ where exercise0_.id=?
DEBUG 18776 --- [nio-8080-exec-4] org.hibernate.SQL                        : select goaltypes0_.exercise_id as exercise1_1_0_, goaltypes0_.goal_types_id as goal_typ2_1_0_, goaltype1_.id as id1_2_1_, goaltype1_.name as name2_2_1_ from operation_movement.exercises_goal_types goaltypes0_ inner join operation_movement.goaltypes goaltype1_ on goaltypes0_.goal_types_id=goaltype1_.id where goaltypes0_.exercise_id=?
DEBUG 18776 --- [nio-8080-exec-4] 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@2de4577a
DEBUG 18776 --- [nio-8080-exec-4] o.s.s.w.a.ExceptionTranslationFilter     : Chain processed normally
DEBUG 18776 --- [nio-8080-exec-4] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
DEBUG 18776 --- [nio-8080-exec-4] o.s.b.w.s.f.OrderedRequestContextFilter  : Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade@29dbd699

返回403响应的POST的Spring日志:

DEBUG 18776 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /newExercise at position 1 of 14 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
 DEBUG 18776 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /newExercise at position 2 of 14 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
 DEBUG 18776 --- [nio-8080-exec-7] w.c.HttpSessionSecurityContextRepository : Obtained a valid SecurityContext from SPRING_SECURITY_CONTEXT: 'org.springframework.security.core.context.SecurityContextImpl@84a2a85a: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@84a2a85a: Principal: com.op.movement.model.ApplicationUserDetails@7b5de4fa; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Not granted any authorities'
 DEBUG 18776 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /newExercise at position 3 of 14 in additional filter chain; firing Filter: 'HeaderWriterFilter'
 DEBUG 18776 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /newExercise at position 4 of 14 in additional filter chain; firing Filter: 'CorsFilter'
 DEBUG 18776 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /newExercise at position 5 of 14 in additional filter chain; firing Filter: 'CsrfFilter'
 DEBUG 18776 --- [nio-8080-exec-7] o.s.security.web.csrf.CsrfFilter         : Invalid CSRF token found for http://localhost:8080/newExercise
 DEBUG 18776 --- [nio-8080-exec-7] 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@2de4577a
 DEBUG 18776 --- [nio-8080-exec-7] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
 DEBUG 18776 --- [nio-8080-exec-7] o.s.b.w.s.f.OrderedRequestContextFilter  : Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade@29dbd699
 DEBUG 18776 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /error at position 1 of 14 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
 DEBUG 18776 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /error at position 2 of 14 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
 DEBUG 18776 --- [nio-8080-exec-7] w.c.HttpSessionSecurityContextRepository : Obtained a valid SecurityContext from SPRING_SECURITY_CONTEXT: 'org.springframework.security.core.context.SecurityContextImpl@84a2a85a: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@84a2a85a: Principal: com.op.movement.model.ApplicationUserDetails@7b5de4fa; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Not granted any authorities'
 DEBUG 18776 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /error at position 3 of 14 in additional filter chain; firing Filter: 'HeaderWriterFilter'
 DEBUG 18776 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /error at position 4 of 14 in additional filter chain; firing Filter: 'CorsFilter'
 DEBUG 18776 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /error at position 5 of 14 in additional filter chain; firing Filter: 'CsrfFilter'
 DEBUG 18776 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /error at position 6 of 14 in additional filter chain; firing Filter: 'LogoutFilter'
 DEBUG 18776 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/error'; against '/logout'
 DEBUG 18776 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /error at position 7 of 14 in additional filter chain; firing Filter: 'ConcurrentSessionFilter'
 DEBUG 18776 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /error at position 8 of 14 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
 DEBUG 18776 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /error at position 9 of 14 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
 DEBUG 18776 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /error at position 10 of 14 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
 DEBUG 18776 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /error at position 11 of 14 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
 DEBUG 18776 --- [nio-8080-exec-7] o.s.s.w.a.AnonymousAuthenticationFilter  : SecurityContextHolder not populated with anonymous token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken@84a2a85a: Principal: com.op.movement.model.ApplicationUserDetails@7b5de4fa; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Not granted any authorities'
 DEBUG 18776 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /error at position 12 of 14 in additional filter chain; firing Filter: 'SessionManagementFilter'
 DEBUG 18776 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /error at position 13 of 14 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
 DEBUG 18776 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /error at position 14 of 14 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
 DEBUG 18776 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/error'; against '/'
 DEBUG 18776 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/error'; against '/main'
 DEBUG 18776 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/error'; against '/user'
 DEBUG 18776 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/error'; against '/runtime.js'
 DEBUG 18776 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/error'; against '/polyfills.js'
 DEBUG 18776 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/error'; against '/main.js'
 DEBUG 18776 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/error'; against '/styles.js'
 DEBUG 18776 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/error'; against '/vendor.js'
 DEBUG 18776 --- [nio-8080-exec-7] o.s.s.w.a.i.FilterSecurityInterceptor    : Secure object: FilterInvocation: URL: /error; Attributes: [authenticated]
 DEBUG 18776 --- [nio-8080-exec-7] o.s.s.w.a.i.FilterSecurityInterceptor    : Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@84a2a85a: Principal: com.op.movement.model.ApplicationUserDetails@7b5de4fa; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Not granted any authorities
 DEBUG 18776 --- [nio-8080-exec-7] o.s.s.access.vote.AffirmativeBased       : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@74ead523, returned: 1
 DEBUG 18776 --- [nio-8080-exec-7] o.s.s.w.a.i.FilterSecurityInterceptor    : Authorization successful
 DEBUG 18776 --- [nio-8080-exec-7] o.s.s.w.a.i.FilterSecurityInterceptor    : RunAsManager did not change Authentication object
 DEBUG 18776 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /error reached end of additional filter chain; proceeding with original chain
 DEBUG 18776 --- [nio-8080-exec-7] o.s.s.w.a.ExceptionTranslationFilter     : Chain processed normally
 DEBUG 18776 --- [nio-8080-exec-7] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed

请尝试使用“POST、PUT、GET、OPTIONS、DELETE”而不是(“GET”、“POST”、“*”)。 - AchillesVan
可能是因为您正在发布到/newExercise,而在authenticatedRequests中没有提到它? - Taranjit Kang
同时,还需要在CORSConfig类上注释@order(Ordered.HIGHEST_PRECEDENCE)。 - AchillesVan
感谢回复!但似乎这些解决方案并没有解决问题。使用完整的操作列表实际上某种程度上破坏了OPTIONS请求。我认为这可能与过滤器顺序有关,但设置CORSConfig顺序似乎并没有解决它... - Mark Bolster
@Taranjit Kang - 不,如果您指的是这段代码片段 .authorizeRequests() .antMatchers("/", "/main", "/user", "/runtime.js","/polyfills.js", "/main.js", "/styles.js", "/vendor.js").permitAll() .anyRequest().authenticated() ------- 这基本上告诉Spring Security那些资源已经被授权,可以被任何人加载。所有其他请求都应该进行身份验证。而/newExercise应该进行身份验证。 - Mark Bolster
2个回答

6

如果有任何人遇到同样的问题,请执行以下操作:

csrf().disable() 

尽管我不知道原因,但我会修复这个问题。似乎在使用 cookies 时,Spring CSRF 和 CORS 会以某种方式发生冲突...

如果我要猜测,下面的内容没有按预期工作。

.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())

这很奇怪,因为它直接引用了Angular:

A CsrfTokenRepository that persists the CSRF token in a cookie named "XSRF-TOKEN" and
reads from the header "X-XSRF-TOKEN" following the conventions of AngularJS. When 
using with AngularJS be sure to use withHttpOnlyFalse().

上述情况似乎是正确的 - 我看到浏览器设置并发送了CSRF令牌,但Spring并没有将其接受为有效。(见上面的日志)
Invalid CSRF token found for http://localhost:8080/newExercise


Request Cookies                         
JSESSIONID  31AD5A7891F8BB83072BFC040AABBB35        
XSRF-TOKEN  579db734-412c-4ce8-82a2-20aa097e47f

目前,禁用CSRF对开发来说是可行的,但在实际应用中,有一个真实场景需要从单独的服务器提供我的Angular应用程序,这是唯一能够向我的Spring服务器发出请求的服务器。希望这些额外的信息可以帮助某些人,并且如果我找到了真正的答案,我会尝试在这里发布。


这只是Angular 6的问题吗? - john
@john 我不确定 - Angular 6 是我唯一熟悉的版本。实际上,我不确定这是否与 Angular 有关。这可能是一个 Spring 的问题。 - Mark Bolster
奇怪...这里 .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse 只对GET操作有效... - Andre

1
尝试将.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())替换为csrfTokenRepositoryCsrfFilter
 .csrfTokenRepository(csrfTokenRepository()).and()
    .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);

请查看完整答案

@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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接