问题:
在代码中,已经添加cookie,如下:
func LoginCheck(c *gin.Context) {
...
c.SetCookie("username",id.(string),1800,"/","localhost",false,true)
c.SetCookie("password",id.(string),1800,"/","localhost",false,true)
...
}
在JS代码中,使用jquery获取cookie,如下:
$(function (){
let username = $.cookie("username");
let password = $.cookie("password");
$("#id").val(username)
$("#pwd").val(password)
});
但页面中仍然无法获取cookie。
解决方法:
首先先看SetCookie 函数的源码:
func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool) {
if path == "" {
path = "/"
}
http.SetCookie(c.Writer, &http.Cookie{
Name: name,
Value: url.QueryEscape(value),
MaxAge: maxAge,
Path: path,
Domain: domain,
SameSite: c.sameSite,
Secure: secure,
HttpOnly: httpOnly,
})
}
可以看到,输入的最后一个参数属于httponly 。
修改之前的代码,修改如下:
c.SetCookie("username",id.(string),1800,"/","localhost",false,false)
此时可以通过jquery获取cookie。
问题产生原因:
首先要知道什么是httponly 。
如果cookie中设置了HttpOnly属性,那么通过js脚本将无法读取到cookie信息,这样能有效的防止XSS攻击,窃取cookie内容,这样就增加了cookie的安全性。
|