当前位置:网站首页>Go learning ----- relevant knowledge of JWT
Go learning ----- relevant knowledge of JWT
2022-07-05 15:09:00 【Week-_-】
List of articles
One 、 Basic introduction
Json web token (JWT), Is a kind of implementation based on the JSON Open standards for ((RFC7519). The token Designed to be compact and safe , Especially for single sign in of distributed sites (SSO) scene .JWT The declaration of is generally used to pass the authenticated user identity information between the identity provider and the service provider , To get resources from the resource server , You can also add some additional declaration information that other business logic requires , The token It can also be used directly for authentication , It can also be encrypted .
Two 、 download
go get -v "github.com/dgrijalva/jwt-go"
3、 ... and 、 Use
1、 Set relevant variables and structures
type JwtClaims struct {
//token Add user information , verification token User information may be used later
jwt.StandardClaims
UserID int `json:"user_id"`
UserName string `json:"user_name"`
Password string `json:"password"`
}
var (
Secret = "YuFen" // Add salt : Signature key
ExpireTime = 20 //token Effective time 20s
)
2、 Create a method generation token
func GetToken(claims *JwtClaims) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodES256, claims) // Follow the specified signature method , and claims To encrypt
signedString, err := token.SignedString([]byte(Secret)) // Generated token Use key signature Secret To encrypt
if err != nil {
return "", err
}
return signedString, nil
}
3 、 stay login() Get build token Information needed
func UserLogin(c *gin.Context) {
var user model.User
user.Name = c.PostForm("Name")
user.Password = c.PostForm("Password")
err := model.UserLogin(user)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"msg": " Login failed ",
//"data":Users,
//401 ( unauthorized ) Request for authentication . For pages that need to log in , The server may return this response .
})
} else {
C, _ = model.GetUser(user.Name)
claims := &utils.JwtClaims{
UserID: C.Id,
UserName: C.Name,
Password: C.Password,
}
claims.IssuedAt = time.Now().Unix()
claims.ExpiresAt = time.Now().Add(time.Second * time.Duration(utils.ExpireTime)).Unix()
s, err := utils.GetToken(claims)
if err != nil {
c.String(http.StatusNotFound, err.Error())
return
}
c.JSON(http.StatusOK, gin.H{
"msg": " Login successful ",
"jwt": s,
})
}
}
4、 Pair generated token To decrypt
func verifyAction(strToken string) (*JWTClaims, error) {
token, err := jwt.ParseWithClaims(strToken, &JWTClaims{
}, func(token *jwt.Token) (interface{
}, error) {
return []byte(Secret), nil // This function is carried by the front end Token Perform relevant decryption , Get the before encryption token data
})
if err != nil {
return nil, errors.New(ErrorReason_ReLogin)
}
claims, ok := token.Claims.(*JWTClaims) // According to the decrypted token obtain claims Statement information
if !ok {
return nil, errors.New(ErrorReason_ReLogin)
}
if err := token.Claims.Valid(); err != nil {
return nil, errors.New(ErrorReason_ReLogin)
}
return claims, nil
verifyAction() There is also a core that is token.Claims.Valid() ( This function is to verify token Is it invalid )
The principle of failure : It's simple , That is in login Obtained when logging in token We have set the expiration time , It's on it 10 second . Then when the function is executed , It will automatically determine whether the current time and expiration time are overdue , Not overdue , It means normal use , Otherwise, an error will be reported and returned , Finally, execute the error response errors.New(ErrorReason_ReLogin)
5、 to update token
func refresh(c *gin.Context) {
strToken := c.Query("token")
claims, err := verifyAction(strToken)
if err != nil {
c.String(http.StatusNotFound, err.Error())
return
}
claims.ExpiresAt = time.Now().Unix() + (claims.ExpiresAt - claims.IssuedAt) // Expiration time
signedToken, err := getToken(claims)
if err != nil {
c.String(http.StatusNotFound, err.Error())
return
}
c.String(http.StatusOK, signedToken)
}
边栏推荐
- 通过npm 或者 yarn安装依赖时 报错 出现乱码解决方式
- 【NVMe2.0b 14-9】NVMe SR-IOV
- 爱可可AI前沿推介(7.5)
- Run faster with go: use golang to serve machine learning
- 【数组和进阶指针经典笔试题12道】这些题,满足你对数组和指针的所有幻想,come on !
- Creation and optimization of MySQL index
- Common MySQL interview questions
- 我这边同时采集多个oracle表,采集一会以后,会报oracle的oga内存超出,大家有没有遇到的?
- 华为哈勃化身硬科技IPO收割机
- Coding devsecops helps financial enterprises run out of digital acceleration
猜你喜欢
How to paste the contents copied by the computer into mobaxterm? How to copy and paste
Behind the ultra clear image quality of NBA Live Broadcast: an in-depth interpretation of Alibaba cloud video cloud "narrowband HD 2.0" technology
Two Bi development, more than 3000 reports? How to do it?
There is a powerful and good-looking language bird editor, which is better than typora and developed by Alibaba
P1451 求细胞数量/1329:【例8.2】细胞
NBA赛事直播超清画质背后:阿里云视频云「窄带高清2.0」技术深度解读
B站做短视频,学抖音死,学YouTube生?
Select sort and bubble sort
做研究无人咨询、与学生不交心,UNC助理教授两年教职挣扎史
Photoshop plug-in action related concepts actionlist actiondescriptor actionlist action execution load call delete PS plug-in development
随机推荐
ICML 2022 | 探索语言模型的最佳架构和训练方法
一键更改多个文件名字
Calculate weight and comprehensive score by R entropy weight method
Jmeter性能测试:ServerAgent资源监控
Leetcode: Shortest Word Distance II
用 Go 跑的更快:使用 Golang 为机器学习服务
R 熵权法计算权重及综合得分
【jvm】运算指令
Garbage collection mechanism of PHP (theoretical questions of PHP interview)
maxcompute有没有能查询 表当前存储容量的大小(kb) 的sql?
P6183 [USACO10MAR] The Rock Game S
[12 classic written questions of array and advanced pointer] these questions meet all your illusions about array and pointer, come on!
Common MySQL interview questions
爱可可AI前沿推介(7.5)
Type declaration of all DOM elements in TS
当代人的水焦虑:好水究竟在哪里?
市值蒸发超百亿美元,“全球IoT云平台第一股”赴港求生
P6183 [USACO10MAR] The Rock Game S
CPU design practice - Chapter 4 practical task 2 using blocking technology to solve conflicts caused by related problems
可转债打新在哪里操作开户是更安全可靠的呢