当前位置:网站首页>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)
}
边栏推荐
- [12 classic written questions of array and advanced pointer] these questions meet all your illusions about array and pointer, come on!
- Machine learning notes - gray wolf optimization
- MongDB学习笔记
- 社区团购撤城“后遗症”
- 裁员下的上海
- The elimination strategy of redis
- 1330: [example 8.3] minimum steps
- Two Bi development, more than 3000 reports? How to do it?
- 想问下大家伙,有无是从腾讯云MYSQL同步到其他地方的呀?腾讯云MySQL存到COS上的binlog
- easyOCR 字符識別
猜你喜欢

How to paste the contents copied by the computer into mobaxterm? How to copy and paste

sql server学习笔记

做研究无人咨询、与学生不交心,UNC助理教授两年教职挣扎史

危机重重下的企业发展,数字化转型到底是不是企业未来救星

Ctfshow web entry explosion

Surpass palm! Peking University Master proposed diverse to comprehensively refresh the NLP reasoning ranking

729. My schedule I: "simulation" & "line segment tree (dynamic open point) &" block + bit operation (bucket Division) "

Fr exercise topic - simple question

Talk about your understanding of microservices (PHP interview theory question)

爱可可AI前沿推介(7.5)
随机推荐
qt creater断点调试程序详解
NBA赛事直播超清画质背后:阿里云视频云「窄带高清2.0」技术深度解读
Visual task scheduling & drag and drop | scalph data integration based on Apache seatunnel
Live broadcast preview | how to implement Devops with automatic tools (welfare at the end of the article)
Ctfshow web entry information collection
Two Bi development, more than 3000 reports? How to do it?
sql server学习笔记
长列表优化虚拟滚动
Selection and use of bceloss, crossentropyloss, sigmoid, etc. in pytorch classification
Install and configure Jenkins
Cartoon: what are the attributes of a good programmer?
ICML 2022 | 探索语言模型的最佳架构和训练方法
1330: [example 8.3] minimum steps
两个BI开发,3000多张报表?如何做的到?
How to solve the problem of garbled code when installing dependency through NPM or yarn
Fr exercise topic --- comprehensive question
我想咨询一下,mysql一个事务对于多张表的更新,怎么保证数据一致性的?
Redis' transaction mechanism
CPU设计实战-第四章实践任务三用前递技术解决相关引发的冲突
你童年的快乐,都是被它承包了