zoukankan      html  css  js  c++  java
  • go-jwt生成token

    JWT生成token

    package util
    
    import (
    	"time"
    
    	jwt "github.com/dgrijalva/jwt-go"
    
    	"github.com/EDDYCJY/go-gin-example/pkg/setting"
    )
    
    var jwtSecret = []byte(setting.JwtSecret)
    
    type Claims struct {
    	Username string `json:"username"`
    	Password string `json:"password"`
    	jwt.StandardClaims
    }
    
    func GenerateToken(username, password string) (string, error) {
    	nowTime := time.Now()
    	expireTime := nowTime.Add(3 * time.Hour)
    
    	claims := Claims{
    		username,
    		password,
    		jwt.StandardClaims {
    			ExpiresAt : expireTime.Unix(),
    			Issuer : "gin-blog",
    		},
    	}
    
    	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
    	token, err := tokenClaims.SignedString(jwtSecret)
    
    	return token, err
    }
    
    func ParseToken(token string) (*Claims, error) {
    	tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
    		return jwtSecret, nil
    	})
    
    	if tokenClaims != nil {
    		if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
    			return claims, nil
    		}
    	}
    
    	return nil, err
    }
    
  • 相关阅读:
    接口开发
    操作Excel
    操作mongodb
    sys模块
    操作redis
    操作数据库
    日志生成、发送邮件
    Codeforces Round #487 (Div. 2)
    bitset学习
    Training for 分块&莫队
  • 原文地址:https://www.cnblogs.com/tomtellyou/p/12552252.html
Copyright © 2011-2022 走看看