- 为什么会有跨域
跨域则是避开浏览器的安全限制
- 同源策略
浏览器最核心也是最基本的安全功能,防止跨站请求资源(如操作 DOM、发请求等)。表现在协议、域名、端口的一致。
- DOM 同源策略风险案例
案例 1: Iframe 嵌入银行登录页面,通过 DOM 节点窃取用户登录信息
- AJAX 同源策略风险案例
案例 2: 用户执行恶意脚本窃取银行网站的 cookie,并携带 cookie 向银行网站发送伪造请求(CSRF)
- 解决方案
(1)jsonp: callback 机制,仅支持 get,依赖后端返回
(2)服务端允许跨域请求,如 java 通过 Spring 注解或过滤器,python flask 通过 Cors 注解等解除服务端限制
```java
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* <p>
* <code>HeaderFilter</code>
* </p>
* Description:
*
* @author: jalchu
* @date: 12/8/2022
**/
@Component()
public class HeaderFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)res;
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin") == null ? "true" : request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE, HEAD");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With, TrackingID, authorization, Access-Control-Allow-Credentials, basic");
response.setContentType("application/json;charset=UTF-8");
chain.doFilter(request, response);
}
}
```
(3)proxy 代理,如 nginx,同源策略仅存在于浏览器
```raw
server {
listen 8082;
server_name 127.0.0.1;
location / {
proxy_pass http://127.0.0.1:8082/ftui;
}
location /ft/ {
proxy_pass http://127.0.0.1:8080/;
proxy_read_timeout 1000;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
```