0

我一直在尝试在我的应用程序中使用来自 Hashicorp Vault 的身份验证方法(从这里)来获取配置。

但无法在 Spring 的文档、示例等中获得有关此身份验证类型的任何信息。请您帮帮我,因为我需要这种类型的身份验证来帮助我在多用户环境中使用 vault。

4

1 回答 1

3

这是我的解决方案:

配置类:

package com.company.myapp.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.vault.VaultException;
import org.springframework.vault.authentication.ClientAuthentication;
import org.springframework.vault.support.VaultToken;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;

@Configuration
public class VaultConfig {

    public static final String LOGIN_PATH = "/v1/auth/userpass/login/";

    @Bean
    public ClientAuthentication clientAuthentication(@Value("${VAULT_USERNAME}") String username,
                                                     @Value("${VAULT_PASSWORD}") String password,
                                                     @Value("${spring.cloud.vault.uri}") String host) {
        return new UserPassAuthentication(host, LOGIN_PATH, username, password);
    }

    public static class UserPassAuthentication implements ClientAuthentication {

        private RestOperations restOperations = new RestTemplate();

        private String url;

        private String password;

        public UserPassAuthentication(String host, String path, String user, String password) {
            this.url = new StringBuilder(host).append(path).append(user).toString();
            this.password = password;
        }

      @Override
    public VaultToken login() throws VaultException {
        return VaultToken.of(
                ((Map<String, String>) restOperations.postForEntity(url, new Password(password), Map.class)
                        .getBody().get("auth")).get("client_token"));
    }
}

static class Password {
    private String password;

    public Password(String password) {
        this.password = password;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

资源/bootstrap.properties:

spring.profiles.active=dev

spring.application.name=myapp
spring.cloud.vault.kv.enabled=true
spring.cloud.vault.kv.backend=test-backend

spring.cloud.vault.uri=https://localhost:8200
VAULT_USERNAME=usr
VAULT_PASSWORD=pwd

资源/META-INF/spring.factories

org.springframework.cloud.bootstrap.BootstrapConfiguration=com.company.myapp.config.VaultConfig
于 2020-02-25T14:23:37.450 回答