如何使用 Spring RESTful Web 服务处理 CSRF 保护? [英] How to handle CSRF protection with Spring RESTful web services?
本文介绍了如何使用 Spring RESTful Web 服务处理 CSRF 保护?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个启用了 CSRF 保护的 Spring Web 应用程序.我可以通过 AJAX 调用访问 RESTful 服务,但是当我使用 httpurlconnection 等其他应用程序访问该服务时,我收到 401 错误(CSRF 令牌为空).
I have a Spring web application with CSRF protection enabled. I am able to access the RESTful service via AJAX calls, but when I am accessing the service with other applications like httpurlconnection, I get a 401 error (CSRF token null).
我知道要访问 RESTful 服务,我需要在请求标头中传递一个令牌,但是如何获取 CSRF 令牌?
I understand that to access the RESTful service I need to pass a token in the request header, but how can I get the CSRF token?
推荐答案
你可以在Spring MVC中创建一个获取CSRF令牌的映射:
You can create a mapping in Spring MVC that gets the CSRF token:
@RequestMapping(value="/csrf-token", method=RequestMethod.GET)
public @ResponseBody String getCsrfToken(HttpServletRequest request) {
CsrfToken token = (CsrfToken)request.getAttribute(CsrfToken.class.getName());
return token.getToken();
}
这篇关于如何使用 Spring RESTful Web 服务处理 CSRF 保护?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文