1 依赖包
package main
import (
"github.com/hashicorp/vault/api"
)
2 vault go-client
var addr string = http://127.0.0.1:8200
//初始化client
func NewVaultClient() (*api.Client, error) {
config := &api.Config{
Address: addr,
}
return api.NewClient(config)
}
3 设置Vault地址和令牌
client.SetAddress("http://127.0.0.1:8200")
client.SetToken("TOKEN")
4 身份验证
func ValidateUser(username,pwd string) error {
// 进行身份验证
_, err = client.Logical().Write("auth/userpass/login/<USERNAME>", map[string]interface{}{
"password": "<PASSWORD>",
})
if err != nil {
fmt.Println("Failed to authenticate:", err)
return err
}
fmt.Println("Authentication successful!")
return nil
}
5 设置密码
func StorePassword(path, key,password string) error {
data := map[string]interface{}{
key: password,
}
_, err := client.Logical().Write("secret/data/" + path, data) // 将密码存储到Vault中
if err != nil {
return err
}
return nil
}
6 获取密码信息
//获取密码信息
func getDatabasePassword() (string, error) {
client, err := getVaultClient()
if err != nil {
return "", err
}
secret, err := client.Logical().Read("secret/data/database")
if err != nil {
return "", err
}
password := secret.Data["password"].(string)
return password, nil
}
7 登录并获取访问令牌
func GetVaultToken(client *api.Client) (string, error) {
options := map[string]interface{}{
"role_id": os.Getenv("VAULT_ROLE_ID"),
"secret_id": os.Getenv("VAULT_SECRET_ID"),
}
response, err := client.Logical().Write("auth/approle/login", options)
if err != nil {
return "", err
}
token, ok := response.Auth.ClientToken
if !ok {
return "", errors.New("failed to retrieve token from Vault")
}
return token, nil
}
8 使用访问令牌
func GetSecretFromVault(client *api.Client, secretPath string) (string, error) {
secret, err := client.Logical().Read(secretPath)
if err != nil {
return "", err
}
if secret == nil {
return "", errors.New("secret not found")
}
data, ok := secret.Data["data"].(map[string]interface{})
if !ok {
return "", errors.New("invalid secret format")
}
key, ok := data["key"].(string)
if !ok {
return "", errors.New("key not found in secret")
}
return key, nil
}
9 加密与解密
// 加密数据
secret, err := client.Logical().Write("transit/encrypt/my-key", map[string]interface{}{
"plaintext": "Hello, World!",
})
if err != nil {
fmt.Println("Failed to encrypt data:", err)
os.Exit(1)
}
// 解密数据
plaintext, err := client.Logical().Write("transit/decrypt/my-key", map[string]interface{}{
"ciphertext": secret.Data["ciphertext"].(string),
})
if err != nil {
fmt.Println("Failed to decrypt data:", err)
os.Exit(1)
}
10 动态凭证管理
// 创建动态凭证
secret, err := client.Logical().Write("database/creds/my-role", nil)
if err != nil {
fmt.Println("Failed to create dynamic credential:", err)
os.Exit(1)
}
// 使用凭证连接数据库
fmt.Println("Connecting to database with dynamic credential:", secret.Data["username"].(string), secret.Data["password"].(string))
参考文档:文章搜索_php中文网