go jwt 사용 사례

990 단어 go.
package main

import (
   "fmt"
   "github.com/dgrijalva/jwt-go"
   "time"
)
//  token
func GenerateToken(user string) (string, error) {
   token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
      "username": user,
      "exp":      time.Now().Add(time.Second * 1).Unix(),
   })
   return token.SignedString([]byte("secret"))
}
func main(){
   tokenStr,_:=GenerateToken("aaa")
   fmt.Println("token is:",tokenStr)
   //  2 ,          
   time.Sleep(time.Duration(2)*time.Second)
   //  token
   token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
      if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
         return nil, fmt.Errorf("not authorization")
      }
      //secret          
      return []byte("secret"), nil
   })
   if err!=nil{
      fmt.Println("err is:",err)
   }
   fmt.Println("token is:",token)
}

좋은 웹페이지 즐겨찾기