Skip to content

Instantly share code, notes, and snippets.

@danesparza
Created June 22, 2017 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danesparza/3a9254236bf6f9f00ebe5ac384656b58 to your computer and use it in GitHub Desktop.
Save danesparza/3a9254236bf6f9f00ebe5ac384656b58 to your computer and use it in GitHub Desktop.
JWT test
package main
import (
"flag"
"fmt"
"github.com/dgrijalva/jwt-go"
"log"
"time"
)
const (
DEFAULT_TOKEN_TEXT = "TOKEN.TO.VERIFY"
)
var (
// You should generate a different key per user
// Here, we're using the same key for everybody
secretKey = "secret"
)
func main() {
log.Println("Starting jwt-test...")
// Set up our flags
verifyToken := flag.String("verify-token", "TOKEN.TO.VERIFY", "The token to verify")
// Parse the command line for flags:
flag.Parse()
// First, see if we have a 'verify-token' flag. If it's the default,
// assume that we need to create a new token
if *verifyToken == DEFAULT_TOKEN_TEXT {
/*
To create PEMs:
openssl genrsa -out private.pem 1024
//extract public key
openssl rsa -in private.pem -out public.pem -outform PEM -pubout
*/
/*
// You can also read the PEM encoded key file in:
key, err := ioutil.ReadFile("private.pem")
if err != nil {
log.Fatal(err)
}
*/
// Create the token (there are multiple signing methods)
token := jwt.New(jwt.SigningMethodHS256)
// Set some claims
token.Claims["foo"] = "bar"
token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
// Sign and get the complete encoded token as a string
tokenString, err := token.SignedString([]byte(secretKey))
if err != nil {
log.Fatal(err)
}
// Here is the token string
log.Println(tokenString)
log.Println("Verify the token at http://jwt.io/")
} else {
// Read the token
token, err := jwt.Parse(*verifyToken, func(token *jwt.Token) (interface{}, error) {
// Validate the alg is what you expect:
if token.Method.Alg() != jwt.SigningMethodHS256.Alg() {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
// Algorithm checks out -- return the key
return []byte(secretKey), nil
})
if err == nil && token.Valid {
fmt.Println("The token is valid")
fmt.Println("Algorithm: " + token.Method.Alg())
} else {
fmt.Println("The token is not valid")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment