UserPass身份验证保险库

时间:2018-04-04 12:48:40

标签: spring-boot hashicorp-vault spring-vault spring-cloud-vault-config

我一直在尝试使用Hashicorp Vault中的身份验证方法(来自here)来获取配置。

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

1 个答案:

答案 0 :(得分:2)

这是我的解决方案:

配置类:

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;
    }
}

resources / 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

resources / META-INF / spring.factories

org.springframework.cloud.bootstrap.BootstrapConfiguration=com.company.myapp.config.VaultConfig