背景:
1、 在使用beego开发后台接口,nginx作为反向代理,ajax请求后台接口。
2 、 beego后台使用session需要验证用户是否登录,但在beego中使用cookie时,针对session默认使用 httponly, 使得session cookie 被存储在response header 中, js无法获取,所以无法用js读取cookie,请求接口时,返回给接口,达到验证。但是在使得session cookie信息,保存在请求时的request headers里,那么后台就可以验证session是否存在。
实现配置
1 在beego的controller函数中 (该服务在 外网服务器 A 上)。
package controllers
import (
"github.com/astaxie/beego"
)
type TestController struct {
beego.Controller
}
func (this *RssController) Check() {
returncode, msg := 0, "success"
result := make(map[string]interface{})
v := this.GetSession("editorname")
if v == nil {
returncode = 1
msg = "log out"
}
result["returncode"] = returncode
result["message"] = msg
this.Data["json"] = result
this.ServeJSON
}
以上通过 GetSession 获取 session信息。 具体有关session的使用,参见 beego 中session module, Session control, 后者是对前者的包装。
该接口的访问路径为: /api/user/check
(在router下配置,将该路径映射到函数Check())
2 nginx 端配置(在 外网服务器 A 上, 假定域名为: testapi.com)
location /api {
add_header 'Access-Control-Allow-Origin' 'http://10.168.10.10:5500';
add_header 'Access-Control-Allow-Credentials' 'true';
proxy_pass http://127.0.0.1:8080/api;
}
3 js 请求(前端在局域网内的机器上,开发工具 visual studio code,)
$.ajax({
type:"GET",
url: "http://testapi.com/api/rss/count",
xhrFields: {
withCredentials: true
},
crossDomain: true,
success: function(resp){
if(resp.returncode == 0)
{
alter("log in");
}
}
})
该机器 ip 假定为 10.168.10.10 (windows ipconfig 获取), 对应端口为 5500,该信息将在上面的nginx中使用。
跨域请求想要带上cookies必须在请求头里面加上用户凭证
{crossDomain: true, xhrFields: {withCredentials: true}}
设置。
由于是用 withCredentials, nginx端会要求是用指定的 Origin,即上面的nginx中的Origin不应该配置成:
add_header 'Access-Control-Allow-Origin' '*';
而是应该配置成:
add_header 'Access-Control-Allow-Origin' 'http://10.168.10.10:5500';