token的使用场景,比如当服务端在多个地方,使用session就需要持久化……。
总的思路:用户在客户端(浏览器)中输入用户名和密码,提交后发送到服务端,服务端验证正确后,生成一个token,将token返回给用户浏览器,浏览器记住这个token,下次访问,携带这个token,服务端先取出这个token,验证正确后放行。
问题:
Authorization: Bearer
搜了不少资料,开始都说要将token放在请求的head里。
//请求中head中设置token
c.Ctx.Output.Header("TOKEN", tokenString)
c.Ctx.Output.Header("Authorization", tokenString)
//设置cookie 名称,值,时间,路径
c.Ctx.SetCookie("TOKEN", tokenString, "3600", "/")
比如,上面2个是放在response的Header,第三个放cookie中。
后来不少地方说放head不安全,放cookie虽然也会不安全,但可以预防……
跨域访问网上都是在ajax等请求中放入token。JWT 也可放在 POST 请求的数据体里面
liuxk: $.ajax({
type: 'GET',
url: url,
contentType: 'text/plain',
xhrFields: {
withCredentials: false
},
headers: {
"token": "xxxxx"
},
success: function(data) {
console.log(data)
},
error: function(error) {
console.log(error)
}
});
$.ajax({
url: host + "/order/autoImport",
method: 'post',
data: excel,
beforeSend: function(request) {
request.setRequestHeader("token", token);
request.setRequestHeader("version", version);
request.setRequestHeader("taskId", currentTask.id);
},
success: function(rs) {
}
})
golang beego:
// 校验token是否有效 返回参数
func CheckToken(tokenString string) (userName string, err error) {
// tokenString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c"
secret := beego.AppConfig.String("TokenSecrets")
// secret = "AllYourBase"
// userName := ""
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// Don't forget to validate the alg is what you expect:
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
return []byte(secret), nil
})
if err != nil {
beego.Error(err)
return "", err
}
// token.Valid里已经包含了过期判断
if token != nil && token.Valid {
// fmt.Println("You look nice today")
claims, _ := token.Claims.(jwt.MapClaims)
userName = claims["userName"].(string)
}
// Token from another example. This token is expired
// token, err = jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// return []byte("secret"), nil
// })
// if token.Valid {
// fmt.Println("You look nice today")
// } else if ve, ok := err.(*jwt.ValidationError); ok {
// if ve.Errors&jwt.ValidationErrorMalformed != 0 {
// fmt.Println("That's not even a token")
// } else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
// // Token is either expired or not active yet
// fmt.Println("Timing is everything")
// } else {
// fmt.Println("Couldn't handle this token:", err)
// }
// } else {
// fmt.Println("Couldn't handle this token:", err)
// }
return userName, err
}
//使用这个生成token
func CreateToken(userName string) (tokenString string, err error) {
token := jwt.New(jwt.SigningMethodHS256)
claims := make(jwt.MapClaims)
//添加令牌关键信息
Tokenexp, err := strconv.Atoi(beego.AppConfig.String("Tokenexp"))
if err != nil {
return tokenString, err
}
//添加令牌期限
claims["exp"] = time.Now().Add(time.Hour * time.Duration(Tokenexp)).Unix()
claims["iat"] = time.Now().Unix()
claims["userName"] = userName
token.Claims = claims
tokenString, err = token.SignedString([]byte(beego.AppConfig.String("TokenSecrets")))
if err != nil {
fmt.Println("generate json web token failed !! error :", err)
return tokenString, err
}
return tokenString, err
}