[英]Spring Boot REST API - enable / disable CSRF protection by client type (browser / non-browser)?
I have a Spring Boot REST API.我有一个 Spring 启动 REST API。 Due to a security policy I need to have CSRF protection enabled for endpoints accessed by the browser.由于安全策略,我需要为浏览器访问的端点启用 CSRF 保护。 However, this API will also be accessed by non-browsers.但是,非浏览器也可以访问此 API。 Is there a way I can create two sets of endpoints, one accessible by browsers only with CSRF enabled and the other accessible by non-browsers only with CSRF disabled?有没有办法可以创建两组端点,一组只能在启用 CSRF 的情况下由浏览器访问,另一组只能在禁用 CSRF 的情况下由非浏览器访问?
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 a RequestMatcher
, like so:当您使用 DSL 配置 CSRF 保护时,例如http.csrf()...
您可以通过传递RequestMatcher
来判断您希望应用 CSRF 保护的请求,如下所示:
http.csrf(csrf -> csrf.requireCsrfProtectionMatcher(new MyBrowserRequestMatcher()));
And your implementation of RequestMatcher
could verify if the HttpServletRequest
contains the header X-Requested-With: XMLHttpRequest
or check the User-Agent
.您的RequestMatcher
实现可以验证HttpServletRequest
是否包含 header X-Requested-With: XMLHttpRequest
或检查User-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.请记住,标头可以更改,您无法保证请求实际上来自浏览器或非浏览器应用程序。
I think you could have separate URL bases for the browser requests and API requests.我认为您可以为浏览器请求和 API 请求提供单独的 URL 基础。
For example, you could have all the endpoints that are to be queried by non-browsers under /api/...
and in your SpringBootSecurityConfiguration
class and configure(HttpSecurity http)
method you could conditionally disable CSRF with http.csrf().disable();
例如,您可以在/api/...
下以及SpringBootSecurityConfiguration
class 和configure(HttpSecurity http)
方法中设置所有要由非浏览器查询的端点,您可以使用http.csrf().disable();
有条件地禁用 CSRF http.csrf().disable();
if the pattern matches (great tutorial can be found here )如果模式匹配(可以在这里找到很棒的教程)
Edit: here is another answer that might be useful.编辑:这是另一个可能有用的答案。
As @ferrouskid said, I created two URL one for browsers and other for non-browsers:正如@ferrouskid 所说,我创建了两个 URL 一个用于浏览器,另一个用于非浏览器:
In spring security config:在 spring 安全配置中:
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.csrf().ignoringAntMatchers("/withoutCsrf/**")
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
.cors().disable();
//complete your configuration }
In controller:在 controller 中:
@Controller
@RequestMapping({"books","withoutCsrf/books"})
public class BookController {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.