登录
首页 >  Golang >  Go教程

go语言beego框架jwt身份认证实现示例

来源:脚本之家

时间:2023-01-07 12:15:54 184浏览 收藏

对于一个Golang开发者来说,牢固扎实的基础是十分重要的,golang学习网就来带大家一点点的掌握基础知识点。今天本篇文章带大家了解《go语言beego框架jwt身份认证实现示例》,主要介绍了JWT、gobeego、身份认证,希望对大家的知识积累有所帮助,快点收藏起来吧,否则需要时就找不到了!

一 引入jwt

jwt用户身份验证

go get github.com/dgrijalva/jwt-go

二 框架中引入jwt

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/dgrijalva/jwt-go"
	"time"
)

三 使用

声明jwt需要用到的结构体

const (
	KEY                    string = "JWT-ARY-STARK"
	DEFAULT_EXPIRE_SECONDS int    = 600 //默认过期时间(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
}

结果 

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
}
//验证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  "
func getHeaderTokenValue(tokenString string) string {
	//Authorization: Bearer 
	return fmt.Sprintf("Bearer %s", tokenString)
}

结果 

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)
	}
}
//验证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身份认证实现示例》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:脚本之家 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>