go語言beego框架jwt身份認(rèn)證實(shí)現(xiàn)示例
一 引入jwt
jwt用戶身份驗(yàn)證
go get github.com/dgrijalva/jwt-go
二 框架中引入jwt
import ( "fmt" "github.com/astaxie/beego" "github.com/dgrijalva/jwt-go" "time" )
三 使用
聲明jwt需要用到的結(jié)構(gòu)體
const ( KEY string = "JWT-ARY-STARK" DEFAULT_EXPIRE_SECONDS int = 600 //默認(rèn)過期時(shí)間(s) ) type User struct { Id string `json:"id"` Name string `json:"json"` } // JWT -- json web token // HEADER PAYLOAD SIGNATURE // This struct is the PAYLOAD type MyCustomClaims struct { User jwt.StandardClaims }
結(jié)果
1234567891011121314151617
封裝方法
//刷新jwt token func RefreshToken(tokenString string) (string, error) { // first get previous token token, err := jwt.ParseWithClaims( tokenString, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) { return []byte(KEY), nil }) claims, ok := token.Claims.(*MyCustomClaims) if !ok || !token.Valid { return "", err } mySigningKey := []byte(KEY) expireAt := time.Now().Add(time.Second * time.Duration(DEFAULT_EXPIRE_SECONDS)).Unix() newClaims := MyCustomClaims{ claims.User, jwt.StandardClaims{ ExpiresAt: expireAt, Issuer: claims.User.Name, IssuedAt: time.Now().Unix(), }, } // generate new token with new claims newToken := jwt.NewWithClaims(jwt.SigningMethodHS256, newClaims) tokenStr, err := newToken.SignedString(mySigningKey) if err != nil { fmt.Println("generate new fresh json web token failed !! error :", err) return "", err } return tokenStr, err } //驗(yàn)證jtw token func ValidateToken(tokenString string) (info User, err error) { token, err := jwt.ParseWithClaims( tokenString, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) { return []byte(KEY), nil }) if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid { //fmt.Printf("%v %v", claims.User, claims.StandardClaims.ExpiresAt) //fmt.Println("token will be expired at ", time.Unix(claims.StandardClaims.ExpiresAt, 0)) info = claims.User } else { fmt.Println("validate tokenString failed !!!", err) } return } //獲取jwt token func GenerateToken(info *User, expiredSeconds int) (tokenString string, err error) { if expiredSeconds == 0 { expiredSeconds = DEFAULT_EXPIRE_SECONDS } // Create the Claims mySigningKey := []byte(KEY) expireAt := time.Now().Add(time.Second * time.Duration(expiredSeconds)).Unix() fmt.Println("token will be expired at ", time.Unix(expireAt, 0)) // pass parameter to this func or not user := *info claims := MyCustomClaims{ user, jwt.StandardClaims{ ExpiresAt: expireAt, Issuer: user.Name, IssuedAt: time.Now().Unix(), }, } token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) tokenStr, err := token.SignedString(mySigningKey) if err != nil { fmt.Println("generate json web token failed !! error :", err) } else { tokenString = tokenStr } return } // return this result to client then all later request should have header "Authorization: Bearer <token> " func getHeaderTokenValue(tokenString string) string { //Authorization: Bearer <token> return fmt.Sprintf("Bearer %s", tokenString) }
結(jié)果
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
使用
//獲取token func (this *UserController) Get() { user := User{1, "gangan"} token, err := GenerateToken(&user, 0); if err != nil { fmt.Println(err) }else { //獲取jwt this.Ctx.WriteString(token) } } //驗(yàn)證token func (this *UserController) Check() { token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwianNvbiI6ImdhbmdhbiIsImV4cCI6MTU3ODU1NDMyOCwiaWF0IjoxNTc4NTUzNzI4LCJpc3MiOiJnYW5nYW4ifQ.jOlMlfLMFBJvyrJTLagrwQx2931LzM7Z0EVMFZ75xYI" info, err := ValidateToken(token) if err != nil { this.Ctx.WriteString(err.Error()) this.StopRun() } fmt.Println(info) this.Ctx.WriteString("success") }
以上就是go語言beego框架jwt身份認(rèn)證實(shí)現(xiàn)示例的詳細(xì)內(nèi)容,更多關(guān)于go beego框架jwt身份認(rèn)證的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
SingleFlight模式的Go并發(fā)編程學(xué)習(xí)
這篇文章主要為大家介紹了SingleFlight模式的Go并發(fā)編程學(xué)習(xí),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-04-04Golang在整潔架構(gòu)基礎(chǔ)上實(shí)現(xiàn)事務(wù)操作
這篇文章在 go-kratos 官方的 layout 項(xiàng)目的整潔架構(gòu)基礎(chǔ)上,實(shí)現(xiàn)優(yōu)雅的數(shù)據(jù)庫(kù)事務(wù)操作,需要的朋友可以參考下2024-08-08go強(qiáng)制類型轉(zhuǎn)換type(a)以及范圍引起的數(shù)據(jù)差異
這篇文章主要為大家介紹了go強(qiáng)制類型轉(zhuǎn)換type(a)以及范圍引起的數(shù)據(jù)差異,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-10-10go內(nèi)存緩存如何new一個(gè)bigcache對(duì)象示例詳解
這篇文章主要為大家介紹了go內(nèi)存緩存如何new一個(gè)bigcache對(duì)象示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-09-09深入分析Go?實(shí)現(xiàn)?MySQL?數(shù)據(jù)庫(kù)事務(wù)
本文深入分析了Go語言實(shí)現(xiàn)MySQL數(shù)據(jù)庫(kù)事務(wù)的原理和實(shí)現(xiàn)方式,包括事務(wù)的ACID特性、事務(wù)的隔離級(jí)別、事務(wù)的實(shí)現(xiàn)方式等。同時(shí),本文還介紹了Go語言中的事務(wù)處理機(jī)制和相關(guān)的API函數(shù),以及如何使用Go語言實(shí)現(xiàn)MySQL數(shù)據(jù)庫(kù)事務(wù)。2023-06-06Go標(biāo)準(zhǔn)庫(kù)strconv實(shí)現(xiàn)string類型與其他基本數(shù)據(jù)類型之間轉(zhuǎn)換
這篇文章主要為大家介紹了Go標(biāo)準(zhǔn)庫(kù)strconv實(shí)現(xiàn)string類型與其他基本數(shù)據(jù)類型之間轉(zhuǎn)換示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11Golang執(zhí)行g(shù)o get私有庫(kù)提示"410 Gone" 的問題及解決辦法
這篇文章主要介紹了Golang執(zhí)行g(shù)o get私有庫(kù)提示”410 Gone“ 解決辦法,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-02-02使用Go語言實(shí)現(xiàn)讀取本地文本文件內(nèi)容
這篇文章主要為大家詳細(xì)介紹了如何使用Go語言實(shí)現(xiàn)讀取本地文本文件內(nèi)容功能,文中的示例代碼簡(jiǎn)潔易懂,有需要的小伙伴可以參考一下2025-07-07