当前位置: 首页 > 知识库问答 >
问题:

Spring Vault客户端-无法连接到本地开发人员Vault服务器

巫朝明
2023-03-14

我在本地安装了保险库。我能够启动本地开发服务器,并根据这个官方教程https://learn.hashicorp.com/Vault/将一些秘密写入/读取到Vault kv中

@Service
public class CredentialsService {

    @Autowired
    private VaultTemplate vaultTemplate;

    public void secureCredentials(Credentials credentials) throws URISyntaxException {
        vaultTemplate.write("credentials/myapp", credentials);
    }

    public Credentials accessCredentials() throws URISyntaxException {
        VaultResponseSupport<Credentials> response = vaultTemplate.read("credentials/myapp", Credentials.class);
        return response.getData();
    }
}

配置类:

@Configuration
public class VaultConfig extends AbstractVaultConfiguration {

    @Override
    public ClientAuthentication clientAuthentication() {
        return new TokenAuthentication("s.EXg6MQwUuB63Z7Xra4zybOut");
    }

    @Override
    public VaultEndpoint vaultEndpoint() {
        return VaultEndpoint.create("host", 8200);
    }
}

还有这个:

@Configuration
@PropertySource(value = { "vault-config.properties" })
@Import(value = EnvironmentVaultConfiguration.class)
public class VaultEnvironmentConfig {

}

一个域对象:

public class Credentials {

    private String username;
    private String password;

    public Credentials() {

    }
    public Credentials(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    @Override
    public String toString() {
        return "Credential [username=" + username + ", password=" + password + "]";
    }
}
@RestController
@ComponentScan
@SpringBootApplication
public class SpringVaultTutorial {

    @Autowired
    CredentialsService credentialsService;

    @RequestMapping("/")
    String home() throws URISyntaxException {
        Credentials credentials = new Credentials("oliver","exxeta123");
        credentialsService.secureCredentials(credentials);
        return credentialsService.accessCredentials().getUsername().toString();
    }

    public static void main(String[] args) {
        SpringApplication.run(SpringVaultTutorial.class, args);
    }

}
server.port: 8443
server.ssl.key-store: keystore.p12
server.ssl.key-store-password: oliver
server.ssl.keyStoreType: PKCS12
server.ssl.keyAlias: tomcat
security.require-ssl=true

修改后,当我调用https://localhost:8443时,我会得到异常:javax.net.SSL.sslexception:无法识别的SSL消息,明文连接?在sun.security.ssl.inputrecord.handleUnknownRecord(inputrecord.java:710)~[NA:1.8.0_121]在sun.security.ssl.inputrecord.read(inputrecord.java:527)~[NA:1.8.0_121]在sun.security.ssl.sslsocketimpl.readRecord(sslsocketimpl.java:973)~[NA:1.8.0_121]在PL.StartHandShake(SSLSockeTimpl.java:1403)~[NA:1.8.0_121]在sun.security.ssl.SSLSockeTimpl.StartHandShake(SSLSockeTimpl.java:1387)~[NA:1.8.0_121]

2)基于教程的第二种方法是关于添加ConnectorConfig类:

@Configuration
public class ConnectorConfig {

    @Bean
    public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat =
                new TomcatServletWebServerFactory() {
                    @Override
                    protected void postProcessContext(Context context) {
                        SecurityConstraint securityConstraint = new SecurityConstraint();
                        securityConstraint.setUserConstraint("CONFIDENTIAL");
                        SecurityCollection collection = new SecurityCollection();
                        collection.addPattern("/*");
                        securityConstraint.addCollection(collection);
                        context.addConstraint(securityConstraint);
                    }
                };
        tomcat.addAdditionalTomcatConnectors(redirectConnector());
        return tomcat;
    }

    private Connector redirectConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(8090);
        connector.setSecure(false);
        connector.setRedirectPort(8443);
        return connector;
    }
}

但是在调用localhost:8090将我重定向到https://localhost:8443之后,我得到了相同的错误:javax.net.SSL.sslexception:无法识别的SSL消息,明文连接?在sun.security.ssl.inputrecord.HandleUnknownRecord(inputrecord.java:710)~

现在的问题是:我是否必须在保险库端配置有关证书的东西?或者您认为Java客户端可能存在证书问题?但我想如果有Java证书问题,在启动时就会抛出异常。

共有1个答案

冯玮
2023-03-14

问题解决了。现在我可以从Java客户机连接到本地保险库。如果将来有人想运行简单的Java客户机库演示,我会在这里粘贴代码。

控制器:

@RestController
@RequestMapping(Paths.ROOT)
@Api(value = Paths.ROOT, description = "Endpoint for core testing")
public class Controller {

    @Autowired
    CredentialsService credentialsService;

    @GetMapping("/")
    String home() throws URISyntaxException {
        Credentials credentials = new Credentials("oliver", "exxeta123");
        credentialsService.secureCredentials(credentials);
        return credentialsService.accessCredentials().toString();
    }

    @GetMapping("/test")
    public String test() throws IOException {
        // http://127.0.0.1:8200/v1/sys/internal/ui/mounts/secret/mysecrets
        VaultConfig vc = new VaultConfig();
        String bearerToken = vc.clientAuthentication().login().getToken();
        System.out.println(bearerToken);
        // credentialsService.accessCredentials()

        // Sending get request
        //URL url = new URL("http://127.0.0.1:8200/v1/sys/internal/ui/mounts/secret/mysecrets");
        // URL updated to match readme.adoc
        URL url = new URL("http://127.0.0.1:8200/v1/kv/my-secret");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setRequestProperty("Authorization", "Bearer " + bearerToken);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestMethod("GET");

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String output;

        StringBuffer response = new StringBuffer();
        while ((output = in.readLine()) != null) {
            response.append(output);
        }

        in.close();
        // printing result from response
        return "Response: - " + response.toString();
    }

    @GetMapping(value = { "/add/{name}/{username}/{password}" })
    public ResponseEntity<String> addKey(@PathVariable(value = "name", required = false, name = "name") String name,
            @PathVariable(value = "username", required = false, name = "username") String username,
            @PathVariable(value = "password", required = false, name = "password") String password) throws URISyntaxException {
        Credentials credentials = new Credentials(username, password);
        credentialsService.secureCredentials(name, credentials);
        return new ResponseEntity<>("Add success: " + credentialsService.accessCredentials(name).getUsername(), HttpStatus.OK);
    }

    @GetMapping(value = {"/get", "/get/{name}"})
    public ResponseEntity<Credentials> getKey(@PathVariable(value = "name", required = false, name = "name") String name) {
        return new ResponseEntity<>(credentialsService.accessCredentials(name), HttpStatus.OK);
    }

    @GetMapping(value= {"/delete", "/delete/{name}"})
    public String removeKey(@PathVariable(value = "name", required = false, name = "name") String name) {
        return "Delete success: " + credentialsService.deleteCredentials(name);
    }

}

服务:

@Service
public class CredentialsService {

    private VaultTemplate vaultTemplate;

    /**
     * To Secure Credentials
     *
     * @param credentials
     * @return VaultResponse
     * @throws URISyntaxException
     */
    public void secureCredentials(Credentials credentials) throws URISyntaxException {
        //vaultTemplate.write("credentials/myapp", credentials);
        initVaultTemplate();
        vaultTemplate.write("kv/myapp", credentials);
    }


    public void secureCredentials(String storagePlace, Credentials credentials) {
        initVaultTemplate();
        vaultTemplate.write("kv/" + storagePlace, credentials);
    }


    /**
     * To Retrieve Credentials
     *
     * @return Credentials
     * @throws URISyntaxException
     */
    public Credentials accessCredentials() throws URISyntaxException {
        //VaultResponseSupport<Credentials> response = vaultTemplate.read("credentials/myapp", Credentials.class);
        initVaultTemplate();
        VaultResponseSupport<Credentials> response = vaultTemplate.read("kv/myapp", Credentials.class);
        return response.getData();
        // TODO special case when there are no values
    }

    /**
     * @param nameOfsecrets key name
     * @return if is presented or empty object
     */
    public Credentials accessCredentials(String nameOfsecrets) {
        initVaultTemplate();
        VaultResponseSupport<Credentials> response = vaultTemplate.read("kv/" + nameOfsecrets, Credentials.class);
        if (response != null) {
            return response.getData();
        } else {
            return new Credentials();
        }
    }

    public boolean deleteCredentials(String name) {
        initVaultTemplate();
        vaultTemplate.delete("kv/" + name);
        return true;
    }
}

private void initVaultTemplate() {
            VaultEndpoint endpoint = new VaultEndpoint();
            endpoint.setHost("localhost");
            endpoint.setPort(8200);
            endpoint.setScheme("http");

            vaultTemplate = new VaultTemplate(endpoint, new VaultConfig().clientAuthentication());
        }
@Configuration
public class VaultConfig extends AbstractVaultConfiguration {

    @Override
    public ClientAuthentication clientAuthentication() {
        return new TokenAuthentication("00000000-0000-0000-0000-000000000000");
    }

    @Override
    public VaultEndpoint vaultEndpoint() {
        return VaultEndpoint.create("localhost", 8200);
    }

}
@Configuration
@PropertySource(value = { "vault-config.properties" })
@Import(value = EnvironmentVaultConfiguration.class)
public class VaultEnvironmentConfig {

}
@SpringBootApplication
@EnableSwagger2
public class SpringVaultTutorial {

    public static void main(String[] args) {
        SpringApplication.run(SpringVaultTutorial.class, args);
    }

    //SWAGGER DOCUMENTATION BEANS
    // default group contains all endpoints
    @Bean
    public Docket defaultApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())//all
                .build().apiInfo(apiInfo());
    }

    // Management group contains Spring Actuator endpoints
    @Bean
    public Docket swaggerAdminEndpoints() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName(Paths.ROOT)
                .apiInfo(apiInfo())
                .select()
                .paths(PathSelectors.regex("/v1/.*"))
                .build()
                .forCodeGeneration(true);
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Vault Demo Application")
                .description("Demo Application using vault")
                .version("1.0")
                .build();
    }

}
    server.port=8443
    server.ssl.key-alias=selfsigned_localhost_sslserver
    server.ssl.key-password=changeit
    server.ssl.key-store=classpath:ssl-server.jks
    server.ssl.key-store-provider=SUN
    server.ssl.key-store-type=JKS

路径:

public class Paths {
    public static final String ROOT = "/v1";
}

全权证书:

public class Credentials {

    private String username;
    private String password;

    public Credentials() {

    }

    public Credentials(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    @Override
    public String toString() {
        return "Credential [username=" + username + ", password=" + password + "]";
    }

}
 类似资料:
  • 我正在使用mac,版本10.14.6,Appium v 1.15和Java8。 我启动Appium作为应用程序,然后试图启动我的自动测试,但有一个失败时,Java试图创建Android驱动程序实例 查看具有功能的屏幕截图 堆栈跟踪 我想这可能是由于Mac的安全策略,因为在Windows上一切都正常。我应该如何解决该问题?

  • 我是OPC UA的新手,我正在使用milo OPC订阅者客户端连接到本地发现服务。我有Prosys模拟服务器,它连接到我的本地发现服务。 注意:如果我直接连接到prosysendpoint,它可以正常工作。它仅通过发现服务失败。 运行代码时会出现以下异常 在ClientRunner中创建客户端的代码。 客户端接口类 订阅服务器运行实现

  • 我无法连接到我的节点。js服务器。当通过节点使用http web服务器在本地运行它时,它工作得很好,但是当连接到外部时,它会加载<code>socket.io。js文件很好,但当尝试使用套接字时,它会从URL中删除端口,无法连接。 而不是在网络请求中执行此操作: http://external-domain.com:3000/socket.io/?EIO=3 它是这样做的: http://exte

  • 问题内容: 我为远程服务器编写了以下hbase客户端类: 它引发了一些异常: 您能告诉我为什么会引发异常,代码有什么问题以及如何解决它。 问题答案: 由于您的HBase服务器的hosts文件,因此会发生此问题。 您只需要编辑HBase服务器的/ etc / hosts文件。 从该文件中删除localhost条目,然后将localhost条目放在HBase服务器IP的前面。 例如,您的HBase服务

  • 问题内容: 由于未知原因,我重新安装了SQL Server 2016,这导致SQL Server崩溃…但是,当我完成安装后,发现无法再连接了。我从SQL Server获得此错误消息。 无法连接到(LocalDB)\ MSSQLLocalDB。 建立与SQL Server的连接时发生与网络相关或特定于实例的错误。服务器未找到或无法访问。验证实例名称正确,并且已将SQL Server配置为允许远程连接

  • 我正在使用spring、spring boot、eureka(用于服务发现)和ribbon开发一个微服务应用程序。 我的应用程序由三个服务组成:客户端、服务器和eureka服务器 客户端和服务器都在eureka服务器上注册,之后客户端使用eureka服务发现调用服务器。 我可以在本地运行应用程序,一切都很好。 但是当部署在aws上时,事情就会失控。 接下来的步骤 同一安全组中有三个ec2实例 每个