Last active
July 4, 2017 09:38
-
-
Save OdinsPlasmaRifle/c00ac0733a6dd611019be75a69dd4418 to your computer and use it in GitHub Desktop.
JWT Tokens using jwt-go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package components | |
import ( | |
"crypto/rsa" | |
jwt "github.com/dgrijalva/jwt-go" | |
"io/ioutil" | |
"log" | |
"time" | |
) | |
const ( | |
privKeyPath = "keys/key.rsa" // openssl genrsa -out key.rsa 2048 | |
pubKeyPath = "keys/key.rsa.pub" // openssl rsa -in key.rsa -pubout > key.rsa.pub | |
) | |
var ( | |
verifyKey *rsa.PublicKey | |
signKey *rsa.PrivateKey | |
) | |
func init() { | |
signBytes, err := ioutil.ReadFile(privKeyPath) | |
fatal(err) | |
signKey, err = jwt.ParseRSAPrivateKeyFromPEM(signBytes) | |
fatal(err) | |
verifyBytes, err := ioutil.ReadFile(pubKeyPath) | |
fatal(err) | |
verifyKey, err = jwt.ParseRSAPublicKeyFromPEM(verifyBytes) | |
fatal(err) | |
} | |
func fatal(err error) { | |
if err != nil { | |
log.Fatal(err) | |
} | |
} | |
func NewToken(userId int) string { | |
// create a signer for rsa 256 | |
t := jwt.New(jwt.GetSigningMethod("RS256")) | |
// set claims | |
t.Claims["user"] = userId | |
t.Claims["iat"] = time.Now().Unix() | |
t.Claims["exp"] = time.Now().Add(time.Second * 3600 * 24).Unix() | |
token, err := t.SignedString(signKey) | |
if err != nil { | |
return "" | |
} | |
return token | |
} | |
func ValidateToken(token string) bool { | |
t, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) { | |
return verifyKey, nil | |
}) | |
if err == nil && t.Valid { | |
return true | |
} | |
return false | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment