CSRF的解决方法
跨站请求伪造(Cross-Site Request Forgery,CSRF)是一种攻击方式,攻击者通过伪造用户的请求,利用用户的身份在用户不知情的情况下执行恶意操作。为了防止CSRF攻击,可以采取以下几种常见的解决方法:
1. 使用CSRF令牌(Token)
这是最常见和有效的防御CSRF攻击的方法。服务器生成一个唯一的令牌,并将其嵌入到每个表单或请求中。服务器在处理请求时验证令牌的有效性。
示例代码(Java Spring Boot)
- 配置CSRF保护:
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.and()
.authorizeRequests()
.anyRequest().authenticated();
}
}
- 在表单中包含CSRF令牌:
<form action="/submit" method="post">
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
<!-- 其他表单字段 -->
<button type="submit">Submit</button>
</form>
2. 验证HTTP Referer头
服务器可以检查请求的 Referer
头,以确保请求来自受信任的源。虽然这种方法不是百分之百可靠,但可以作为额外的防御措施。
示例代码(Java Servlet)
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
public class CsrfFilter implements Filter {
private static final String TRUSTED_REFERER = "https://trusted.com";
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String referer = httpRequest.getHeader("Referer");
if (referer != null && referer.startsWith(TRUSTED_REFERER)) {
chain.doFilter(request, response);
} else {
((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN, "CSRF protection");
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
@Override
public void destroy() {}
}
3. 使用SameSite Cookie属性
SameSite
属性可以防止浏览器在跨站请求中发送Cookie。将 SameSite
属性设置为 Strict
或 Lax
可以有效防止CSRF攻击。
示例代码(Java Servlet)
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
public class SameSiteCookieFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse) response;
Cookie[] cookies = ((HttpServletRequest) request).getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
cookie.setHttpOnly(true);
cookie.setSecure(true);
cookie.setPath("/");
cookie.setMaxAge(3600);
cookie.setSameSite("Strict"); // 或者 "Lax"
httpResponse.addCookie(cookie);
}
}
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
@Override
public void destroy() {}
}
4. 双重提交Cookie
在这种方法中,服务器会在响应中设置一个CSRF令牌Cookie,并在每个请求中要求客户端将该令牌作为请求参数发送回来。服务器验证请求中的令牌和Cookie中的令牌是否匹配。
示例代码(Java Servlet)
- 设置CSRF令牌Cookie:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.UUID;
public class CsrfTokenFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse) response;
String csrfToken = UUID.randomUUID().toString();
Cookie csrfCookie = new Cookie("CSRF-TOKEN", csrfToken);
csrfCookie.setHttpOnly(true);
csrfCookie.setSecure(true);
csrfCookie.setPath("/");
httpResponse.addCookie(csrfCookie);
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
@Override
public void destroy() {}
}
- 验证CSRF令牌:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
public class CsrfValidationFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
String csrfToken = httpRequest.getParameter("csrfToken");
Cookie[] cookies = httpRequest.getCookies();
String csrfCookieValue = null;
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("CSRF-TOKEN".equals(cookie.getName())) {
csrfCookieValue = cookie.getValue();
break;
}
}
}
if (csrfToken != null && csrfToken.equals(csrfCookieValue)) {
chain.doFilter(request, response);
} else {
httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "CSRF protection");
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
@Override
public void destroy() {}
}
总结
防止CSRF攻击的方法有很多,最常见和有效的方法是使用CSRF令牌。其他方法如验证HTTP Referer头、使用SameSite Cookie属性和双重提交Cookie也可以作为辅助措施。根据具体的应用场景和需求,可以选择一种或多种方法来保护你的应用免受CSRF攻击。