1. 基础知识
1.1 同源策略
同源:指在同一个域,就是两个页面具有相同的协议、域名、端口。
同源策略 (Sameoriginpolicy)是一种约定,它是浏览器最核心也是最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。同源策略会阻止一个域的javascript脚本和另外一个域的内容进行交互。
1.2 什么是跨域
当一个请求 url 的 协议、域名、端口 三者之间任意一个与当前页面的 url 不同时,即为跨域
当前页面 URL | 被请求页面 URL | 是否跨域 | 原因 |
---|---|---|---|
http://www.test.com/ | http://www.test.com/index.html | 否 | 同源 |
http://www.test.com/ | https://www.test.com/index.html | 跨域 | 协议不同 (http != https) |
http://www.test.com/ | http://www.baidu.com | 跨域 | 主域名不同 (test != baidu) |
http://www.test.com/ | http://blog.test.com/ | 跨域 | 子域名不同 (www != blog) |
http://www.test.com:8080/ | http://www.test.com:7001/ | 跨域 | 端口不同 (8080 != 7001) |
1.3 非同源限制
关于跨域的解决方法,大部分可以分为两种:
- nginx 反向代理解决跨域
- 服务端设置 Response Header(响应头部)的 Access-Control-Allow-Origin
对于后端开发者来说,第 2 种的操作性更为灵活,一般都用第2。
2. 简单请求
2.1 CORS标准
CORS是一个W3C标准,全称是”跨域资源共享”(Cross-origin resource sharing)。它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。
2.2 简单请求的结构
浏览器将 CORS 请求分成两类:简单请求(simple request)和非简单请求(not-so-simple request)。 只要同时满足以下两大条件,就属于简单请求。
这是为了兼容表单(form),因为历史上表单一直可以发出跨域请求。AJAX 的跨域设计就是,只要表单可以发,AJAX 就可以直接发。
凡是不同时满足上面两个条件,就属于非简单请求。浏览器对这两种请求的处理,是不一样的
2.3 请求的基本流程
对于简单请求,浏览器直接发出CORS请求。具体来说,就是在头信息之中,增加一个 Origin 字段 。 下面是一个例子,浏览器发现这次跨源AJAX请求是简单请求,就自动在头信息之中,添加一个 Origin 字段。
上面的头信息中,Origin字段用来说明,本次请求来自哪个源(协议 + 域名 + 端口)。服务器根据这个值,决定是否同意这次请求。
如果Origin指定的源,不在许可范围内(不同源),服务器会返回一个正常的HTTP回应。浏览器发现,这个回应的头信息没有包含 Access-Control-Allow-Origin 字段(详见下文),就知道出错了,从而抛出一个错误,被XMLHttpRequest 的 onerror 回调函数捕获。注意,这种错误无法通过状态码识别,因为HTTP回应的状态码有可能是200。
如果Origin指定的域名在许可范围内(同源),服务器返回的响应,会多出几个头信息字段
上面的头信息之中,有三个与CORS请求相关的字段,都以 Access-Control- 开头。
(1)Access-Control-Allow-Origin
该字段是必须的。它的值要么是请求时 Origin 字段的值,要么是一个*,表示接受任意域名的请求。
(2)Access-Control-Allow-Credentials
该字段可选。它的值是一个布尔值,表示是否允许发送Cookie。默认情况下,Cookie不包括在CORS请求之中。设为true,即表示服务器明确许可,Cookie可以包含在请求中,一起发给服务器。这个值也只能设为true,如果服务器不要浏览器发送Cookie,删除该字段即可。
(3)Access-Control-Expose-Headers
该字段可选,用来指定可另外拿到的字段。CORS请求时,XMLHttpRequest对象的getResponseHeader( )方法只能拿到6个基本字段:Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma。
如果想拿到其他字段,就必须在 Access-Control-Expose-Headers 里面指定。上面的例子指定,getResponseHeader(‘FooBar’)可以返回FooBar字段的值
【关于非简单请求以及更详细的内容,请参考阮一峰的博客:http://www.ruanyifeng.com/blog/2016/04/cors.html】
3. 原生gin解决跨域
在 Gin 中提供了 middleware(中间件) 来做到在一个请求前后处理响应的逻辑。编写一个 Cors 中间件,在每次响应请求前均在请求上添加 Access-Control-Allow-Origin 头部
3.1 编写Cors中间件
该中间件是一个闭包,主要使用的方法为 c.Header,作用是用指定参数修改请求头
在 middleware 包下编写:
package middleware
import (
"github.com/gin-gonic/gin"
"net/http"
)
func Cors() gin.HandlerFunc{
return func(c *gin.Context) {
method := c.Request.Method
origin := c.Request.Header.Get("Origin")
if origin != ""{
// 接收客户端发送的origin (重要!)
c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
//服务器支持的所有跨域请求的方法
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
//允许跨域设置可以返回其他子段,可以自定义字段
c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session")
// 允许浏览器(客户端)可以解析的头部 (重要)
c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers")
//设置缓存时间
c.Header("Access-Control-Max-Age", "172800")
//允许客户端传递校验信息比如 cookie (重要)
c.Header("Access-Control-Allow-Credentials", "true")
}
if method == "OPTIONS" {
c.AbortWithStatus(http.StatusOK)
}
c.Next()
}
}
3.2 调用Cors
package main
import (
"github.com/gin-gonic/gin"
"go_code/first_web/middleware"
)
func Test() gin.HandlerFunc{
return func(c *gin.Context) {
}
}
func main() {
r := gin.New()
r.Use(middleware.Cors())
r.GET("xxx",Test())
}
4. github.com/gin-contrib/cors 包
4.1 下载+导入
下载:
go get github.com/gin-contrib/cors
导入
import "github.com/gin-contrib/cors"
4.2 使用
package main
import (
"time"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
// CORS for https://foo.com and https://github.com origins, allowing:
// - PUT and PATCH methods
// - Origin header
// - Credentials share
// - Preflight requests cached for 12 hours
router.Use(cors.New(cors.Config{
AllowOrigins: []string{"https://foo.com"},
AllowMethods: []string{"PUT", "PATCH"},
AllowHeaders: []string{"Origin"},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: true,
AllowOriginFunc: func(origin string) bool {
return origin == "https://github.com"
},
MaxAge: 12 * time.Hour,
}))
router.Run()
}
Using DefaultConfig as start point
func main() {
router := gin.Default()
// - No origin allowed by default
// - GET,POST, PUT, HEAD methods
// - Credentials share disabled
// - Preflight requests cached for 12 hours
config := cors.DefaultConfig()
config.AllowOrigins = []string{"http://google.com"}
// config.AllowOrigins == []string{"http://google.com", "http://facebook.com"}
router.Use(cors.New(config))
router.Run()
}
该包能够解决跨域主要取决于函数 **New**,该函数将设置请求头为指定的参数,函数原型为:<br /><br />其入参为一个 **Config **结构体,结构体的字段包含允许跨域时请求头所需要的参数,原型为:
/ Config represents all available options for the middleware.
type Config struct {
AllowAllOrigins bool
// AllowOrigins is a list of origins a cross-domain request can be executed from.
// If the special "*" value is present in the list, all origins will be allowed.
// Default value is []
AllowOrigins []string
// AllowOriginFunc is a custom function to validate the origin. It take the origin
// as argument and returns true if allowed or false otherwise. If this option is
// set, the content of AllowOrigins is ignored.
AllowOriginFunc func(origin string) bool
// AllowMethods is a list of methods the client is allowed to use with
// cross-domain requests. Default value is simple methods (GET and POST)
AllowMethods []string
// AllowHeaders is list of non simple headers the client is allowed to use with
// cross-domain requests.
AllowHeaders []string
// AllowCredentials indicates whether the request can include user credentials like
// cookies, HTTP authentication or client side SSL certificates.
AllowCredentials bool
// ExposedHeaders indicates which headers are safe to expose to the API of a CORS
// API specification
ExposeHeaders []string
// MaxAge indicates how long (in seconds) the results of a preflight request
// can be cached
MaxAge time.Duration
// Allows to add origins like http://some-domain/*, https://api.* or http://some.*.subdomain.com
AllowWildcard bool
// Allows usage of popular browser extensions schemas
AllowBrowserExtensions bool
// Allows usage of WebSocket protocol
AllowWebSockets bool
// Allows usage of file:// schema (dangerous!) use it only when you 100% sure it's needed
AllowFiles bool
}
当然,也可以在 middleware 里编写中间件 <br /><br />然后在路由上挂载该中间件:
func main() {
r := gin.New()
r.Use(middleware.Cors())
r.GET("xxx",Test())
}