简体   繁体   English

具有Security&REST端点的Spring MVC给出了403“由于未找到您的会话,因此无法验证提供的CSRF令牌”

[英]Spring MVC with Security & REST endpoint gives a 403 “Could not verify the provided CSRF token because your session was not found”

I have a Java Spring-boot microservice where I have an admin website and REST endpoints. 我有一个Java Spring-boot微服务,其中有一个管理网站和REST端点。 The website is accessed at myserver.com/serverwebpages and the REST web service is at myserver.com/api/restendpoints. 可从myserver.com/serverwebpages访问该网站,而REST Web服务则位于myserver.com/api/restendpoints。 I am using Spring MVC with login security and CSRF on the web side and HMAC Authorization on the REST endpoint side. 我正在将Spring MVC与Web侧的登录安全性和CSRF以及REST端点侧的HMAC授权一起使用。 I have @Controller annotation on the website side and @RestController annotation for the REST web service. 我在网站端有@Controller批注,在REST Web服务中有@RestController批注。 The website works fine and the webservice works fine with GET's. 该网站运行正常,而Web服务与GET的运行良好。 However, I just tried a DELETE and got a 403, error:forbidden, message:"Could not verify the provided CSRF token because your session was not found". 但是,我只是尝试了DELETE并收到403,错误:禁止,消息:“由于未找到您的会话,因此无法验证提供的CSRF令牌”。 It looks like the MVC security is seeing REST webservice requests and calling out the CSRF error because I have not provided a CSRF number. 似乎MVC安全正在看到REST Web服务请求并指出CSRF错误,因为我没有提供CSRF编号。 Of course, I do provide CSRF's on the web page side for MVC cross-scripting security. 当然,我确实在网页一侧提供了CSRF,以确保MVC跨脚本的安全性。 Anyone know how to fix this? 有人知道怎么修这个东西吗? Do I need to create a separate microservice with a different port? 我是否需要使用其他端口创建单独的微服务?

When you call DELETE method, they need CSRF token. 当您调用DELETE方法时,它们需要CSRF令牌。 Maybe your DELETE API doesn't carry CSRF token. 也许您的DELETE API不带有CSRF令牌。 You need to add CSRF token in Request Header. 您需要在“请求标头”中添加CSRF令牌。

Adding CSRF in Header is depends on Ajax framework. 在Header中添加CSRF取决于Ajax框架。 If your combination is Spring-Security + Thymeleaf + jQuery, then refer Spring Security Document : 如果您的组合是Spring-Security + Thymeleaf + jQuery,请参阅Spring Security Document:
https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html#csrf-include-csrf-token-ajax https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html#csrf-include-csrf-token-ajax

I could not figure out a solution to the problem using Spring MVC. 我无法使用Spring MVC找到解决问题的方法。 So I just created 2 separate microservices on the same AWS instance. 因此,我只是在同一AWS实例上创建了2个单独的微服务。 One microservice with port number 443 handles the web services and uses Spring MVC. 一个端口号为443的微服务处理Web服务并使用Spring MVC。 The other microservice with port 8443 handles all of the REST API calls with no Spring MVC. 另一个带有端口8443的微服务无需Spring MVC即可处理所有REST API调用。 This worked perfectly. 这工作得很好。 Disappointed that I could not find an answer but had to move on. 令我失望的是我找不到答案,只能继续前进。

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

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