当前位置:网站首页>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)
}
边栏推荐
- R 熵权法计算权重及综合得分
- 机器学习笔记 - 灰狼优化
- Magic methods and usage in PHP (PHP interview theory questions)
- Mongdb learning notes
- 1330:【例8.3】最少步数
- Huiyuan, 30, is going to have a new owner
- Photoshop插件-动作相关概念-ActionList-ActionDescriptor-ActionList-动作执行加载调用删除-PS插件开发
- GPS original coordinates to Baidu map coordinates (pure C code)
- Brief introduction of machine learning framework
- 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?
猜你喜欢
Run faster with go: use golang to serve machine learning
【数组和进阶指针经典笔试题12道】这些题,满足你对数组和指针的所有幻想,come on !
Implement a blog system -- using template engine technology
【华为机试真题详解】字符统计及重排
选择排序和冒泡排序
MySQL之CRUD
[detailed explanation of Huawei machine test] character statistics and rearrangement
【jvm】运算指令
市值蒸发超百亿美元,“全球IoT云平台第一股”赴港求生
Machine learning notes - gray wolf optimization
随机推荐
Leetcode: Shortest Word Distance II
CODING DevSecOps 助力金融企业跑出数字加速度
长列表优化虚拟滚动
Detailed explanation of QT creator breakpoint debugger
CPU设计实战-第四章实践任务二用阻塞技术解决相关引发的冲突
MySQL----函数
我想咨询一下,mysql一个事务对于多张表的更新,怎么保证数据一致性的?
What are CSRF, XSS, SQL injection, DDoS attack and timing attack respectively and how to prevent them (PHP interview theory question)
华为哈勃化身硬科技IPO收割机
729. 我的日程安排表 I :「模拟」&「线段树(动态开点)」&「分块 + 位运算(分桶)」
危机重重下的企业发展,数字化转型到底是不是企业未来救星
IPv6与IPv4的区别 网信办等三部推进IPv6规模部署
Creation and optimization of MySQL index
MySQL之CRUD
【NVMe2.0b 14-9】NVMe SR-IOV
[JVM] operation instruction
Two Bi development, more than 3000 reports? How to do it?
MySQL之CRUD
P6183 [USACO10MAR] The Rock Game S
Talking about how dataset and dataloader call when loading data__ getitem__ () function