当前位置:网站首页>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)
}
边栏推荐
- Calculate weight and comprehensive score by R entropy weight method
- 通过npm 或者 yarn安装依赖时 报错 出现乱码解决方式
- easyOCR 字符識別
- TS所有dom元素的类型声明
- [recruitment position] infrastructure software developer
- Differences between IPv6 and IPv4 three departments including the office of network information technology promote IPv6 scale deployment
- 美团优选管理层变动:老将刘薇调岗,前阿里高管加盟
- PyTorch二分类时BCELoss,CrossEntropyLoss,Sigmoid等的选择和使用
- Run faster with go: use golang to serve machine learning
- Cartoon: programmers don't repair computers!
猜你喜欢

qt creater断点调试程序详解

Common MySQL interview questions

MongDB学习笔记

Under the crisis of enterprise development, is digital transformation the future savior of enterprises

Garbage collection mechanism of PHP (theoretical questions of PHP interview)

Interview shock 62: what are the precautions for group by?

729. 我的日程安排表 I :「模拟」&「线段树(动态开点)」&「分块 + 位运算(分桶)」

There is a powerful and good-looking language bird editor, which is better than typora and developed by Alibaba

PyTorch二分类时BCELoss,CrossEntropyLoss,Sigmoid等的选择和使用

Huiyuan, 30, is going to have a new owner
随机推荐
Visual task scheduling & drag and drop | scalph data integration based on Apache seatunnel
Common interview questions about swoole
729. My schedule I: "simulation" & "line segment tree (dynamic open point) &" block + bit operation (bucket Division) "
基于TI DRV10970驱动直流无刷电机
CODING DevSecOps 助力金融企业跑出数字加速度
选择排序和冒泡排序
R 熵权法计算权重及综合得分
漫画:优秀的程序员具备哪些属性?
Fr exercise topic --- comprehensive question
Install and configure Jenkins
Shanghai under layoffs
Behind the ultra clear image quality of NBA Live Broadcast: an in-depth interpretation of Alibaba cloud video cloud "narrowband HD 2.0" technology
安装配置Jenkins
Handwriting promise and async await
Machine learning notes - gray wolf optimization
Ten billion massage machine blue ocean, difficult to be a giant
浅谈Dataset和Dataloader在加载数据时如何调用到__getitem__()函数
anaconda使用中科大源
What are the domestic formal futures company platforms in 2022? How about founder metaphase? Is it safe and reliable?
Fr exercise topic - simple question