- During config file creation, the generated JWT key will be stored. - Added an option to disable this behavior.
49 lines
890 B
Go
49 lines
890 B
Go
package jwtauth
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"encoding/base64"
|
|
"os"
|
|
)
|
|
|
|
func generateRandomBytes(n int) ([]byte, error) {
|
|
b := make([]byte, n)
|
|
_, err := rand.Read(b)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return b, nil
|
|
}
|
|
|
|
func generateSecureToken(n int) (string, error) {
|
|
bytes, err := generateRandomBytes(n)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return base64.URLEncoding.EncodeToString(bytes), nil
|
|
}
|
|
|
|
func getKeyVariableName() string {
|
|
return "PLM_JWT_KEY"
|
|
}
|
|
|
|
func InitKey(jwtkey string) (string, error) {
|
|
var err error
|
|
keyName := getKeyVariableName()
|
|
//ignore config value, look in env first
|
|
key := os.Getenv(keyName)
|
|
if key == "" {
|
|
if jwtkey != "" {
|
|
key = jwtkey
|
|
} else {
|
|
key, err = generateSecureToken(64)
|
|
}
|
|
os.Setenv(keyName, key)
|
|
}
|
|
return key, err
|
|
}
|
|
|
|
func GetJwtKey() ([]byte, error) {
|
|
return base64.URLEncoding.DecodeString(os.Getenv(getKeyVariableName()))
|
|
}
|