当前位置:网站首页>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)
}
边栏推荐
- IPv6与IPv4的区别 网信办等三部推进IPv6规模部署
- 危机重重下的企业发展,数字化转型到底是不是企业未来救星
- How can I quickly check whether there is an error after FreeSurfer runs Recon all—— Core command tail redirection
- Magic methods and usage in PHP (PHP interview theory questions)
- NBA赛事直播超清画质背后:阿里云视频云「窄带高清2.0」技术深度解读
- 数据库学习——数据库安全性
- CPU design related notes
- Fr exercise topic --- comprehensive question
- P6183 [USACO10MAR] The Rock Game S
- Type declaration of all DOM elements in TS
猜你喜欢
Garbage collection mechanism of PHP (theoretical questions of PHP interview)
Dark horse programmer - software testing -10 stage 2-linux and database -44-57 why learn database, description of database classification relational database, description of Navicat operation data, de
MongDB学习笔记
超级哇塞的快排,你值得学会!
Ctfshow web entry explosion
Under the crisis of enterprise development, is digital transformation the future savior of enterprises
Crud de MySQL
Two Bi development, more than 3000 reports? How to do it?
[detailed explanation of Huawei machine test] character statistics and rearrangement
基于TI DRV10970驱动直流无刷电机
随机推荐
手写promise与async await
通过npm 或者 yarn安装依赖时 报错 出现乱码解决方式
Un week - end heureux
Under the crisis of enterprise development, is digital transformation the future savior of enterprises
1330: [example 8.3] minimum steps
Install and configure Jenkins
IPv6与IPv4的区别 网信办等三部推进IPv6规模部署
MySQL之CRUD
Interview shock 62: what are the precautions for group by?
Ten billion massage machine blue ocean, difficult to be a giant
sql server char nchar varchar和nvarchar的区别
Talking about how dataset and dataloader call when loading data__ getitem__ () function
Leetcode: Shortest Word Distance II
两个BI开发,3000多张报表?如何做的到?
【NVMe2.0b 14-9】NVMe SR-IOV
Detailed explanation of QT creator breakpoint debugger
Super wow fast row, you are worth learning!
js亮瞎你眼的日期选择器
qt creater断点调试程序详解
漫画:程序员不是修电脑的!