rob*_*ins 15 java rest csrf spring-security spring-boot
I have a REST service, built using Java, Spring-boot and using Spring Security with Basic Access Authentication. There are no Views, no JSP etc, no 'login', just stateless services which can be called from a React app hosted separately.
I've read a variety of documentation about CSRF protection, but can't decide whether I should be using spring-security CSRF config, or just disabling it? If I disable the csrf protection I can call the service with curl using my basic auth like this:
curl -H "authorization:Basic c35sdfsdfjpzYzB0dDFzaHA=" -H "content-type:application/json" -d '{"username":"user","password":"password","roles":"USER"}' localhost:8081/api/v1/user
Run Code Online (Sandbox Code Playgroud)
If I enable the csrf protection and provide a x-csrf-token header, then the spring CsrfFilter attempts to cross check this against a value from (I think) a session cookie in the HttpServletRequest. However since its a stateless REST service I don't have a session, and haven't 'logged in'.
I have a config class which looks like this:
@EnableWebSecurity
@Configuration
public class ServiceSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().fullyAuthenticated()
.and().httpBasic();
if (!serviceProperties.isCsrfEnabled()) {
http.csrf().disable();
}
}
Run Code Online (Sandbox Code Playgroud)
我想得越多,我就越觉得我只需要禁用 CSRF 保护。有没有另一种方法来配置 spring 安全性以便它可以工作?
谢谢
Ser*_*scu 22
要回答您的第一个问题,在您描述的上下文中,您不需要 CSRF 保护。CSRF 保护的背景是确保用户不会被诱骗做一些不需要的操作。
例如,在纯理论中,您可以登录银行网站(并因此建立会话),然后访问某个可疑网站。该站点可以有一个向银行 API 发出 POST 请求的表单。因为你在那里有一个会话,如果端点不受 CSRF 保护,那么请求可能会通过。
因此,CSRF 主要用作防御基于浏览器 + 会话的攻击。如果您公开具有例如 OAuth 保护的纯 REST API,那么我看不到 CSRF 的任何理由。
当您使用 spring boot 时,您还可以使用application.properties/application.yaml配置文件禁用 CSRF 。
security.enable-csrf=false
Run Code Online (Sandbox Code Playgroud)
您可以查看Common Application Properties文档页面以获取更多开箱即用的配置选项。
| 归档时间: |
|
| 查看次数: |
12537 次 |
| 最近记录: |