当前位置:网站首页>Golang JWT cross domain authentication
Golang JWT cross domain authentication
2022-07-27 04:05:00 【Crisp_ LF】
Golang jwt Cross domain authentication
JWT Full name JSON Web Token Is a cross domain authentication solution , It belongs to an open standard , It stipulates a kind of Token Realization way , At present, it is mostly used for front and rear end separation projects and OAuth2.0
install jwt
go get github.com/dgrijalva/jwt-go
Generate jwt
package main
import (
"errors"
"fmt"
jwt "github.com/dgrijalva/jwt-go"
"time"
)
type MyClaims struct {
// Except under the feet Claims, You also need user information
Username string `json:"username"`
Password string `json:"password"`
//jwt Medium standard Claims
jwt.StandardClaims
}
var key = []byte("secret")
//GenToken Generate token Methods
func GenToken(username string, password string) (string, error) {
// Create our own statement
c := MyClaims{
username, // Custom field
password,
jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Hour * 2).Unix(), // Expiration time
Issuer: "Crisp", // Issued by people
},
}
// Creates a signature object using the specified signature method
token := jwt.NewWithClaims(jwt.SigningMethodHS256, c) // Use here HS256 encryption algorithm
// Use specified secret Sign and get the complete encoded string token
// Note that this place must be a byte slice, not a string
return token.SignedString(key)
}
analysis jwt
//ParseToken analysis token Methods
func ParseToken(tokenString string) (*MyClaims, error) {
// analysis token
token, err := jwt.ParseWithClaims(tokenString, &MyClaims{
},
func(token *jwt.Token) (i interface{
}, err error) {
return key, nil
})
if err != nil {
return nil, err
}
if claims, ok := token.Claims.(*MyClaims); ok && token.Valid {
// check token
return claims, nil
}
return nil, errors.New("invalid token")
}
Call to generate token And analyze token
func main() {
// Generate token
token, err := GenToken("Crisp", "12345678")
if err != nil {
panic(err)
}
// analysis token
parseToken, err := ParseToken(token)
if err != nil {
panic(err)
}
fmt.Printf("parseToken.UserName: %v\n", parseToken.Username)
fmt.Printf("parseToken.Password: %v\n", parseToken.Password)
}
Code run results
Generated token:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IkNyaXNwIiwicGFzc3dvcmQiOiIxMjM0NTY3OCIsImV4cCI6MTY1ODcyNzQxNXNzIjoiQ3Jpc3AifQ.wXUoWlv8VeMJo_ezWSlsEO_XOfcwh3aD4Y_q0YoZfDg
analysis token:
analysis token get :parseToken.UserName: Crisp
analysis token get :parseToken.Password: 12345678
边栏推荐
- Golang发送邮件库email
- Share the current life -- a six week internship experience of a high school graduate in CCTV
- An online duplicate of a hidden bug
- C# 使用SqlSugar Updateable系统报错无效数字,如何解决?求指导!
- 【安卓小叙】Kotlin多线程编程(一)
- C # using sqlsugar updatable system to report invalid numbers, how to solve it? Ask for guidance!
- Use websocket to realize a web version of chat room (fishing is more hidden)
- Greenplum [deployment 08] database small version upgrade process and problem handling error: open-source-greenplum-db-6 conflicts with
- 商业打假系列之第一百之--无聊的制度和管理流程真的可以扔进垃圾桶-顺便分析十几个无用的Unity游戏自检项目
- Okaleido tiger is about to log in to binance NFT in the second round, which has aroused heated discussion in the community
猜你喜欢

Process analysis of object creation

次轮Okaleido Tiger即将登录Binance NFT,引发社区热议

11.zuul路由网关

科目三: 济南章丘五号线

288 page 180000 word intelligent campus overall design directory

On the first day of Shenzhen furniture exhibition, the three highlights of Jin Ke'er booth were unlocked!

Lixia action | Yuanqi Digitalization: existing mode or open source innovation?

NLP hotspots from ACL 2022 onsite experience

Chapter 5 decision tree and random forest practice

C语言学习笔记 —— 内存管理
随机推荐
Will this flinkcdc monitor all tables in the database? Or the designated table? I look at the background log. It monitors all tables. If it monitors
VR全景制作在家装行业是谈单利器?这是为什么呢?
Bean Validation原理篇--07
Prime factorization -- C (GCC) -- PTA
Maximum subarray cumulative sum less than or equal to K
注释有点好玩哦
Notes are a little fun
Use websocket to realize a web version of chat room (fishing is more hidden)
04.在谷歌浏览器中安装模拟浏览器ChromeDriver的详细步骤
Leetcode- > dichotomy (III)
A. YES or YES?
VR全景现在是不是刚需?看完你就明白了
JS array de duplication (including simple array de duplication and object array de duplication)
一维数组的应用
【SemiDrive源码分析】【驱动BringUp】41 - LCM 驱动 backlight 背光控制原理分析
Cocos game practice-04-collision detection and NPC rendering
Redis(九) - Redis之分布式锁
Leetcode- > 2-point search and clock in (3)
Lixia action | Yuanqi Digitalization: existing mode or open source innovation?
Kettle reads file split by line