jwtgen/main.go

73 lines
1.9 KiB
Go
Raw Normal View History

2021-09-09 16:34:53 +02:00
package main
import (
"flag"
"fmt"
"os"
"time"
"github.com/dgrijalva/jwt-go"
)
func main() {
secret := os.Getenv("JWT_SECRET")
if secret == "" {
fmt.Println("No secret in environment")
}
hostname, err := os.Hostname()
if err != nil {
fmt.Println(err)
return
}
fmt.Println(hostname)
usernameFlag := flag.String("username", "demo", "username to use when generating jwt token")
issuerFlag := flag.String("issuer", "issuer.golang.com", "issuer to use when generating jwt token")
expireFlag := flag.Int("expire", 0, "expire how many hours when generating jwt token")
adminFlag := flag.Bool("admin", false, "should the user be admin?")
writeFlag := flag.Bool("write", false, "should the user be able to write?")
readFlag := flag.Bool("read", true, "should the user be able to read?")
flag.Parse()
var token *jwt.Token
if *expireFlag == 0 {
token = jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"username": *usernameFlag,
"admin": *adminFlag,
"write": *writeFlag,
"read": *readFlag,
"iss": *issuerFlag,
"iat": time.Now().Unix(),
})
} else {
token = jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"username": *usernameFlag,
"admin": *adminFlag,
"write": *writeFlag,
"read": *readFlag,
"iss": *issuerFlag,
"exp": time.Now().Add(time.Hour * time.Duration(*expireFlag)).Unix(),
"iat": time.Now().Unix(),
})
}
tokenString, err := token.SignedString([]byte(secret))
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("Generated JWT token for\n")
fmt.Printf("Username: %s\n", *usernameFlag)
fmt.Printf("Admin: %v\n", *adminFlag)
fmt.Printf("Write: %v\n", *writeFlag)
fmt.Printf("Read: %v\n", *readFlag)
fmt.Printf("Issuer: %s\n", *issuerFlag)
fmt.Printf("Expire: %d hours\n", *expireFlag)
fmt.Println("-------- Token --------")
fmt.Printf("%s\n", tokenString)
fmt.Println("-----------------------")
}