Home > Article > Backend Development > How to Securely Store Private Keys for JWT Generation in Google App Engine?
Hosting Private Key in Google App Engine
Using the "github.com/dgrijalva/jwt-go" library to create JSON web tokens involves the use of a private key. While this key can be easily utilized when hosting locally, deploying to Google App Engine (GAE) presents a challenge due to the lack of file system access.
Options for Key Storage
When hosting on GAE, there are two primary options for storing the private key:
Static File Storage
To store the private key as a static file in GAE, it can be placed in the app's root directory, and referenced using a relative path. For example, a key located at key/my_key.txt can be accessed as key/my_key.txt.
Datastore Storage
To store the private key in the Datastore, a KeyEntity can be created:
import ( "context" "cloud.google.com/go/datastore" ) type KeyEntity struct { Key string } func StoreKey(ctx context.Context) error { client, err := datastore.NewClient(ctx, projectID) if err != nil { return err } _, err = client.Put(ctx, datastore.NameKey("Key", "key", nil), &KeyEntity{Key: privateKey}) return err }
The stored key can then be accessed through the GetKey function:
func GetKey(ctx context.Context) (string, error) { client, err := datastore.NewClient(ctx, projectID) if err != nil { return "", err } var keyEntity KeyEntity if err = client.Get(ctx, datastore.NameKey("Key", "key", nil), &keyEntity); err != nil { return "", err } return keyEntity.Key, nil }
Note: Static files are not available to the app's code. Therefore, referencing a private key stored as a static file requires careful configuration to ensure the file is available to the app.
The above is the detailed content of How to Securely Store Private Keys for JWT Generation in Google App Engine?. For more information, please follow other related articles on the PHP Chinese website!