/*
jwt - 生成token测试
1.首先需要定义一个结构体,这个结构体选哟继承jwt.StandardClain,s 结构体
2.定义key 和过期时间
3.实例化存储token的结构体
4.使用指定的签名方法创建签名对象
5.使用指定的 secret 签名 并获得完整的编码后的字符串 token
*/
// 1.首先需要定义一个结构体,这个结构体选哟继承jwt.StandardClain,s 结构体
type MyClaims struct {
Uid int //自定义的属性 用于不同接口传值
jwt.StandardClaims
}
// 2.定义key 和过期时间
var jwtKey = []byte("huazai.com")
var expireTime = time.Now().Add(24 * time.Hour).Unix()
func (con V1Controller) Login(c *gin.Context) {
// 3.实例化存储token的结构体
myClaimsObj := MyClaims{
23,
jwt.StandardClaims{
ExpiresAt: expireTime,
Issuer: "huazai",
},
}
// 4.使用指定的签名方法创建签名对象
tokenObj := jwt.NewWithClaims(jwt.SigningMethodHS256, myClaimsObj)
// 5.使用指定的 secret 签名 并获得完整的编码后的字符串 token
tokenStr, err := tokenObj.SignedString(jwtKey)
fmt.Println(tokenStr)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"message": "生成token失败重试",
"success": false,
})
return
}
c.JSON(http.StatusOK, gin.H{
"message": "获取token成功",
"token": tokenStr,
"success": true,
})
}
// 测试从前端发起的请求头中拿到token
func (con V1Controller) AddressList(c *gin.Context) {
//获取token
tokenData := c.Request.Header.Get("Authorization")
fmt.Println("---------")
fmt.Println(tokenData)
if len(tokenData) > 0 {
fmt.Println("---------")
tokenStr := strings.Split(tokenData, " ")[1]
fmt.Println(tokenStr)
token, myClaims, err := ParseToken(tokenStr)
if err != nil || !token.Valid {
c.JSON(http.StatusOK, gin.H{
"message": "token传入错误",
"success": false,
})
} else {
c.JSON(http.StatusOK, gin.H{
"message": "验证token成功",
"Uid": myClaims.Uid,
"success": true,
})
}
}
}
type Address struct {
Username string `form:"username" json:"username"`
Address string `form:"address" json:"address"`
Tel string `form:"tel" json:"tel"`
}
//测试从post请求中拿到数据以及token验证
func (con V1Controller) Address(c *gin.Context) {
//获取数据 post
var address Address
b, _ := c.GetRawData()
json.Unmarshal(b, &address)
fmt.Println(address)
//获取token
tokenData := c.Request.Header.Get("Authorization")
if len(tokenData) > 0 {
tokenStr := strings.Split(tokenData, " ")[1]
token, myClaims, err := ParseToken(tokenStr)
if err != nil || !token.Valid {
c.JSON(http.StatusOK, gin.H{
"message": "传入token错误",
"success": false,
})
return
} else {
c.JSON(http.StatusOK, gin.H{
"message": "验证token成功",
"Uid": myClaims.Uid,
"success": true,
})
}
}
}
// 验证token是否合法
func ParseToken(tokenStr string) (*jwt.Token, *MyClaims, error) {
myClaims := &MyClaims{}
token, err := jwt.ParseWithClaims(tokenStr, myClaims, func(token *jwt.Token) (i interface{}, err error) {
return jwtKey, nil
})
return token, myClaims, err
}
路由
func ApiRoutersInit(r *gin.Engine) {<template> <div class="about"> <h2>JWT demo</h2>
apiRouters := r.Group("/api/v1")
{
apiRouters.GET("/navList", api.V1Controller{}.Navlist)
apiRouters.POST("/doLogin", api.V1Controller{}.DoLogin)
apiRouters.PUT("/editArticle", api.V1Controller{}.EditArticle)
apiRouters.DELETE("/deleteNav", api.V1Controller{}.DeleteNav)
//jwt测试
apiRouters.GET("/login", api.V1Controller{}.Login)
apiRouters.GET("/addressList", api.V1Controller{}.AddressList)
apiRouters.POST("/addAddress", api.V1Controller{}.Address)
}
}
前端请求接口
<br /> <button @click="getAddress">获取收货地址</button>
<br /> <br /> <br /> <button @click="addAddress">增加收货地址</button> </div> </template>
<script> export default { name: "home", data() { return { msg: "this is about", }; }, methods: { getAddress() { var token = localStorage.getItem("token"); this.$axios .get("http://localhost:8080/api/v1/addressList", { headers: { Authorization: "Bearer " + token, }, }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); }, addAddress() { var token = localStorage.getItem("token"); this.$axios .post( "http://localhost:8080/api/v1/addAddress", { username: "张三" }, { headers: { Authorization: "Bearer " + token, }, } ) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); }, }, }; </script> 标签:令牌,V1Controller,jwt,tokenStr,token,api,go,gin From: https://www.cnblogs.com/lunar-huazai/p/17222151.html