Spring Boot REST API - 按客户端类型(浏览器/非浏览器)启用/禁用 CSRF 保护?
我有一个 Spring Boot REST API。由于安全策略的原因,我需要为浏览器访问的端点启用 CSRF 保护。但是,非浏览器也可以访问此 API。有没有办法创建两组端点,一组只能在启用 CSRF 的情况下由浏览器访问,另一组只能在禁用 CSRF 的情况下由非浏览器访问?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当您使用 DSL 配置 CSRF 保护时,例如
http.csrf()...
,您可以通过传递RequestMatcher
来判断您希望应用 CSRF 保护的请求>,就像这样:您的
RequestMatcher
实现可以验证HttpServletRequest
是否包含标头X-Requested-With: XMLHttpRequest
或检查用户代理
。请记住,标头可以更改,并且您不能保证请求实际上来自浏览器或非浏览器应用程序。
When you configure your CSRF protection using the DSL, like this
http.csrf()...
you can tell which requests you want the CSRF protection to be applied by passing aRequestMatcher
, like so:And your implementation of
RequestMatcher
could verify if theHttpServletRequest
contains the headerX-Requested-With: XMLHttpRequest
or check theUser-Agent
.Just keep in mind that the headers can be changed and you have no guarantee that the request actually come from a browser or non-browser app.
我认为您可以为浏览器请求和 API 请求使用单独的 URL 库。
例如,您可以在
/api/...
下和SpringBootSecurityConfiguration
类中拥有非浏览器要查询的所有端点,并configure( HttpSecurity http)
方法,如果模式匹配,您可以使用http.csrf().disable();
有条件地禁用 CSRF(可以找到很棒的教程 这里)编辑:这里是另一个答案可能有用。
I think you could have separate URL bases for the browser requests and API requests.
For example, you could have all the endpoints that are to be queried by non-browsers under
/api/...
and in yourSpringBootSecurityConfiguration
class andconfigure(HttpSecurity http)
method you could conditionally disable CSRF withhttp.csrf().disable();
if the pattern matches (great tutorial can be found here)Edit: here is another answer that might be useful.
正如 @ferrouskid 所说,我创建了两个 URL,一个用于浏览器,另一个用于非浏览器:
在 spring 安全配置中:
在控制器中:
As @ferrouskid said, I created two URL one for browsers and other for non-browsers:
In spring security config:
In controller:
由于依赖请求头可能无法准确识别请求来源,因此创建单独的服务 url,一个用于浏览器客户端,一个用于非浏览器客户端,并对非浏览器服务禁用 CSRF 保护也可以考虑作为一种解决方案。
创建 SecurityFilterChain 时可以禁用特定 URL 的 CSRF 保护。
Since relying on request headers may not accurately identify the source of requests, creating separate service urls, one for browser and one for non browser clients and disabling CSRF protection for non browser service can also be considered as a solution.
CSRF protection for specific URLs can be disabled while creating SecurityFilterChain.