We intend to set cookie for *.1234tv.com in login.1234tv.com. However it does not work.
I have configure the container as below:
beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
AllowAllOrigins: true,
AllowOrigins: []string{"http://*.1234tv.com"},
AllowMethods: []string{"GET", "POST", "PUT", "DELETE","PATCH","HEAD", "OPTIONS"},
AllowHeaders: []string{"Origin", "Authorization", "Access-Control-Allow-Origin", "Content-Type"},
ExposeHeaders: []string{"Content-Length", "Access-Control-Allow-Origin"},
AllowCredentials: true,
}))
and set cookie in controller like this:
this.Ctx.SetCookie("UNION_TOKEN", utoken, 3600*24*7,"/", ".1234tv.com",false,false)
The cause is set-cookie by response does not work. 1.Since it is an across sites Ajax request, .withCredentials() can active the ability of set cookie by response.
$.ajax( {
/* Setup the call */
xhrFields: {
withCredentials: true
}
});
2.On the side of response server, "Access-Control-Allow-Credentials
" must be "true
" and "Access-Control-Allow-Origin
" must not be "*
" and "Access-Control-Allow-Origin" could be "http://*.domain.com
".
I find a solution to this question
beego.InsertFilter("*",beego.BeforeRouter,func(ctx *context.Context) {
ctx.ResponseWriter.Header().Add("Access-Control-Allow-Origin", "*")
ctx.ResponseWriter.Header().Add("Access-Control-Allow-Credentials", "true")
})
if you want to send cookie in http,use "http://XX" instead of "*",or you can set "Access-Control-Allow-Origin" seprately in an API,like that:
beego.InsertFilter("*",beego.BeforeRouter,func(ctx *context.Context) {
ctx.ResponseWriter.Header().Add("Access-Control-Allow-Origin", "*")
ctx.ResponseWriter.Header().Add("Access-Control-Allow-Credentials", "true")
})
func (c *ArticleController)AddArticle(){
c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "http://XX")
}
$.ajax( {
...
xhrFields: {
withCredentials: true
}
});