Skip to content

Instantly share code, notes, and snippets.

@gufranmirza gufranmirza/token.go
Created Jun 21, 2019

Embed
What would you like to do?
package main
import (
"time"
"github.com/dgrijalva/jwt-go"
)
func generateTokenPair() (map[string]string, error) {
// Create token
token := jwt.New(jwt.SigningMethodHS256)
// Set claims
// This is the information which frontend can use
// The backend can also decode the token and get admin etc.
claims := token.Claims.(jwt.MapClaims)
claims["sub"] = 1
claims["name"] = "Jon Doe"
claims["admin"] = true
claims["exp"] = time.Now().Add(time.Minute * 15).Unix()
// Generate encoded token and send it as response.
// The signing string should be secret (a generated UUID works too)
t, err := token.SignedString([]byte("secret"))
if err != nil {
return nil, err
}
refreshToken := jwt.New(jwt.SigningMethodHS256)
rtClaims := refreshToken.Claims.(jwt.MapClaims)
rtClaims["sub"] = 1
rtClaims["exp"] = time.Now().Add(time.Hour * 24).Unix()
rt, err := refreshToken.SignedString([]byte("secret"))
if err != nil {
return nil, err
}
return map[string]string{
"access_token": t,
"refresh_token": rt,
}, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.