当前位置:网站首页>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)
}
边栏推荐
- Photoshop plug-in action related concepts actionlist actiondescriptor actionlist action execution load call delete PS plug-in development
- TS所有dom元素的类型声明
- P6183 [USACO10MAR] The Rock Game S
- 【NVMe2.0b 14-9】NVMe SR-IOV
- Two Bi development, more than 3000 reports? How to do it?
- 可转债打新在哪里操作开户是更安全可靠的呢
- Redis' transaction mechanism
- Reasons and solutions for redis cache penetration and cache avalanche
- I collect multiple Oracle tables at the same time. After collecting for a while, I will report that Oracle's OGA memory is exceeded. Have you encountered it?
- Under the crisis of enterprise development, is digital transformation the future savior of enterprises
猜你喜欢
There is a powerful and good-looking language bird editor, which is better than typora and developed by Alibaba
Huawei Hubble incarnation hard technology IPO harvester
No one consults when doing research and does not communicate with students. UNC assistant professor has a two-year history of teaching struggle
Au - delà du PARM! La maîtrise de l'Université de Pékin propose diverse pour actualiser complètement le classement du raisonnement du NLP
用 Go 跑的更快:使用 Golang 为机器学习服务
Creation and optimization of MySQL index
美团优选管理层变动:老将刘薇调岗,前阿里高管加盟
Interpretation of Apache linkage parameters in computing middleware
MySQL----函数
How to paste the contents copied by the computer into mobaxterm? How to copy and paste
随机推荐
go学习 ------jwt的相关知识
Huiyuan, 30, is going to have a new owner
Two Bi development, more than 3000 reports? How to do it?
Garbage collection mechanism of PHP (theoretical questions of PHP interview)
PHP high concurrency and large traffic solution (PHP interview theory question)
ICML 2022 | 探索语言模型的最佳架构和训练方法
Ecotone technology has passed ISO27001 and iso21434 safety management system certification
[JVM] operation instruction
【C 题集】of Ⅷ
Live broadcast preview | how to implement Devops with automatic tools (welfare at the end of the article)
Stop B makes short videos, learns Tiktok to die, learns YouTube to live?
想问下大家伙,有无是从腾讯云MYSQL同步到其他地方的呀?腾讯云MySQL存到COS上的binlog
Behind the ultra clear image quality of NBA Live Broadcast: an in-depth interpretation of Alibaba cloud video cloud "narrowband HD 2.0" technology
社区团购撤城“后遗症”
可视化任务编排&拖拉拽 | Scaleph 基于 Apache SeaTunnel的数据集成
[detailed explanation of Huawei machine test] character statistics and rearrangement
729. My schedule I: "simulation" & "line segment tree (dynamic open point) &" block + bit operation (bucket Division) "
Interview shock 62: what are the precautions for group by?
Ten billion massage machine blue ocean, difficult to be a giant
【华为机试真题详解】字符统计及重排