Java Code Examples for org.springframework.vault.authentication.TokenAuthentication

The following examples show how to use org.springframework.vault.authentication.TokenAuthentication. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Test
void reactiveNamespaceSecretsAreIsolated() {

	VaultTemplate marketing = new VaultTemplate(this.maketingRestTemplate,
			new SimpleSessionManager(new TokenAuthentication(this.marketingToken)));

	ReactiveVaultTemplate reactiveMarketing = new ReactiveVaultTemplate(this.marketingWebClientBuilder,
			() -> Mono.just(VaultToken.of(this.marketingToken)));

	marketing.write("marketing-secrets/my-secret", Collections.singletonMap("key", "marketing"));

	assertThat(marketing.read("marketing-secrets/my-secret")).isNotNull();

	reactiveMarketing.read("marketing-secrets/my-secret").as(StepVerifier::create).consumeNextWith(actual -> {
		assertThat(actual.getRequiredData()).containsEntry("key", "marketing");
	}).verifyComplete();
}
 
Example 2
Source Project: cloudbreak   Source File: VaultConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ClientAuthentication clientAuthentication() {
    if (AUTH_TYPE_K8S.equalsIgnoreCase(authType)) {
        LOGGER.info("Kubernetes based Vault auth is configured");
        try {
            String token = FileReaderUtils.readFileFromPath(Paths.get(kubernetesSATokenPath));
            KubernetesAuthenticationOptions k8sOptions = KubernetesAuthenticationOptions.builder()
                    .jwtSupplier(() -> token)
                    .role(kubernetesLoginRole)
                    .path(kubernetesMountPath)
                    .build();
            return new KubernetesAuthentication(k8sOptions, restOperations());
        } catch (IOException e) {
            throw new RuntimeException("Failed to read the Kubernetes service account token", e);
        }
    } else {
        LOGGER.info("Token based Vault auth is configured");
        return new TokenAuthentication(rootToken);
    }
}
 
Example 3
@Test
public void configureClientAuthenticationIfOnlyTokenSetThenTokenMethod() {
    KeyVaultConfig keyVaultConfig = mock(KeyVaultConfig.class);
    EnvironmentVariableProvider envProvider = mock(EnvironmentVariableProvider.class);
    ClientHttpRequestFactory clientHttpRequestFactory = mock(ClientHttpRequestFactory.class);
    VaultEndpoint vaultEndpoint = mock(VaultEndpoint.class);

    when(envProvider.getEnv(HASHICORP_ROLE_ID)).thenReturn(null);
    when(envProvider.getEnv(HASHICORP_SECRET_ID)).thenReturn(null);
    when(envProvider.getEnv(HASHICORP_TOKEN)).thenReturn("token");

    ClientAuthentication result = util.configureClientAuthentication(keyVaultConfig, envProvider, clientHttpRequestFactory, vaultEndpoint);

    assertThat(result).isInstanceOf(TokenAuthentication.class);
}
 
Example 4
/**
 * Construct a {@link VaultTokenSupplier} using {@link #clientAuthentication()}.
 * @return the {@link VaultTokenSupplier} for Vault session token management.
 * @see VaultTokenSupplier
 * @see #clientAuthentication()
 */
protected VaultTokenSupplier vaultTokenSupplier() {

	ClientAuthentication clientAuthentication = clientAuthentication();

	Assert.notNull(clientAuthentication, "ClientAuthentication must not be null");

	if (clientAuthentication instanceof TokenAuthentication) {

		TokenAuthentication authentication = (TokenAuthentication) clientAuthentication;
		return () -> Mono.just(authentication.login());
	}

	if (clientAuthentication instanceof AuthenticationStepsFactory) {

		AuthenticationStepsFactory factory = (AuthenticationStepsFactory) clientAuthentication;

		WebClient webClient = getWebClientFactory().create();
		AuthenticationStepsOperator stepsOperator = new AuthenticationStepsOperator(
				factory.getAuthenticationSteps(), webClient);

		return CachingVaultTokenSupplier.of(stepsOperator);
	}

	throw new IllegalStateException(String.format(
			"Cannot construct VaultTokenSupplier from %s. "
					+ "ClientAuthentication must implement AuthenticationStepsFactory or be TokenAuthentication",
			clientAuthentication));
}
 
Example 5
@Test
void shouldConfigureTokenAuthentication() {

	ClientAuthentication clientAuthentication = this.configuration.clientAuthentication();

	assertThat(clientAuthentication).isInstanceOf(TokenAuthentication.class);
	assertThat(clientAuthentication.login()).isEqualTo(VaultToken.of("my-token"));
}
 
Example 6
@Test
void namespaceSecretsAreIsolated() {

	VaultTemplate dev = new VaultTemplate(this.devRestTemplate,
			new SimpleSessionManager(new TokenAuthentication(this.devToken)));
	VaultTemplate marketing = new VaultTemplate(this.maketingRestTemplate,
			new SimpleSessionManager(new TokenAuthentication(this.marketingToken)));

	dev.write("dev-secrets/my-secret", Collections.singletonMap("key", "dev"));
	marketing.write("marketing-secrets/my-secret", Collections.singletonMap("key", "marketing"));

	assertThat(dev.read("marketing-secrets/my-secret")).isNull();
	assertThat(marketing.read("marketing-secrets/my-secret")).isNotNull();
}
 
Example 7
@Test
void shouldReportInitialized() {

	VaultTemplate marketing = new VaultTemplate(this.maketingRestTemplate,
			new SimpleSessionManager(new TokenAuthentication(this.marketingToken)));

	assertThat(marketing.opsForSys().isInitialized()).isTrue();
}
 
Example 8
@Test
void shouldReportHealth() {

	VaultTemplate marketing = new VaultTemplate(this.maketingRestTemplate,
			new SimpleSessionManager(new TokenAuthentication(this.marketingToken)));

	assertThat(marketing.opsForSys().health().isInitialized()).isTrue();
}
 
Example 9
Source Project: spring-cloud-vault   Source File: VaultNamespaceTests.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void before() {
	Assume.assumeTrue("Namespaces require enterprise version",
			this.vaultRule.prepare().getVersion().isEnterprise());

	List<String> namespaces = new ArrayList<>(Arrays.asList("dev/", "marketing/"));
	List<String> list = this.vaultRule.prepare().getVaultOperations()
			.list("sys/namespaces");
	namespaces.removeAll(list);

	for (String namespace : namespaces) {
		this.vaultRule.prepare().getVaultOperations()
				.write("sys/namespaces/" + namespace.replaceAll("/", ""));
	}

	this.maketingRestTemplate = RestTemplateBuilder.builder()
			.requestFactory(ClientHttpRequestFactoryFactory
					.create(new ClientOptions(), Settings.createSslConfiguration()))
			.endpoint(TestRestTemplateFactory.TEST_VAULT_ENDPOINT)
			.defaultHeader(VaultHttpHeaders.VAULT_NAMESPACE, "marketing");

	VaultTemplate marketing = new VaultTemplate(this.maketingRestTemplate,
			new SimpleSessionManager(new TokenAuthentication(Settings.token())));

	mountKv(marketing, "marketing-secrets");
	marketing.opsForSys().createOrUpdatePolicy("relaxed", POLICY);
	this.marketingToken = marketing.opsForToken()
			.create(VaultTokenRequest.builder().withPolicy("relaxed").build())
			.getToken().getToken();
}
 
Example 10
Source Project: spring-cloud-vault   Source File: VaultNamespaceTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReportHealth() {

	VaultTemplate marketing = new VaultTemplate(this.maketingRestTemplate,
			new SimpleSessionManager(new TokenAuthentication(this.marketingToken)));

	Health.Builder builder = Health.unknown();
	new VaultHealthIndicator(marketing).doHealthCheck(builder);

	assertThat(builder.build().getStatus()).isEqualTo(Status.UP);
}
 
Example 11
@Override
public ClientAuthentication getClientAuthentication(
		VaultEnvironmentProperties vaultProperties,
		RestOperations vaultRestOperations, RestOperations externalRestOperations) {

	Assert.hasText(vaultProperties.getToken(),
			missingPropertyForAuthMethod("token", AuthenticationMethod.TOKEN));

	return new TokenAuthentication(vaultProperties.getToken());
}
 
Example 12
@Test
public void tokenAuthentication() {
	properties.setAuthentication(TOKEN);
	properties.setToken("token");

	assertClientAuthenticationOfType(properties, TokenAuthentication.class);
}
 
Example 13
private SpringVaultClientConfiguration mockClientConfiguration() {
	VaultTemplate vaultTemplate = new VaultTemplate(
			VaultEndpoint.create("localhost", 8200),
			new TokenAuthentication("token"));

	SpringVaultClientConfiguration clientConfiguration = mock(
			SpringVaultClientConfiguration.class);
	when(clientConfiguration.vaultTemplate()).thenReturn(vaultTemplate);

	return clientConfiguration;
}
 
Example 14
Source Project: vault-crd   Source File: VaultConfiguration.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public ClientAuthentication clientAuthentication() {
    return new TokenAuthentication(vaultToken);
}
 
Example 15
Source Project: spring-vault   Source File: SecurePropertyUsage.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public ClientAuthentication clientAuthentication() {
	return new TokenAuthentication(getEnvironment().getProperty("vault.token"));
}
 
Example 16
Source Project: spring-vault   Source File: VaultApp.java    License: Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {

		VaultTemplate vaultTemplate = new VaultTemplate(new VaultEndpoint(),
				new TokenAuthentication("00000000-0000-0000-0000-000000000000"));

		Secrets secrets = new Secrets();
		secrets.username = "hello";
		secrets.password = "world";

		vaultTemplate.write("secret/myapp", secrets);

		VaultResponseSupport<Secrets> response = vaultTemplate.read("secret/myapp", Secrets.class);
		System.out.println(response.getRequiredData().getUsername());

		vaultTemplate.delete("secret/myapp");
	}
 
Example 17
@Override
public ClientAuthentication clientAuthentication() {
	return new TokenAuthentication(Settings.token());
}
 
Example 18
@Override
public ClientAuthentication clientAuthentication() {
	return new TokenAuthentication(Settings.token());
}
 
Example 19
@Override
public ClientAuthentication clientAuthentication() {
	return new TokenAuthentication(Settings.token());
}
 
Example 20
@BeforeEach
void before() {

	Assumptions.assumeTrue(prepare().getVersion().isEnterprise(), "Namespaces require enterprise version");

	List<String> namespaces = new ArrayList<>(Arrays.asList("dev/", "marketing/"));
	List<String> list = prepare().getVaultOperations().list("sys/namespaces");
	namespaces.removeAll(list);

	for (String namespace : namespaces) {
		prepare().getVaultOperations().write("sys/namespaces/" + namespace.replaceAll("/", ""));
	}

	this.devRestTemplate = RestTemplateBuilder.builder()
			.requestFactory(
					ClientHttpRequestFactoryFactory.create(new ClientOptions(), Settings.createSslConfiguration()))
			.endpoint(TestRestTemplateFactory.TEST_VAULT_ENDPOINT).customizers(restTemplate -> restTemplate
					.getInterceptors().add(VaultClients.createNamespaceInterceptor("dev")));

	this.maketingRestTemplate = RestTemplateBuilder.builder()
			.requestFactory(
					ClientHttpRequestFactoryFactory.create(new ClientOptions(), Settings.createSslConfiguration()))
			.endpoint(TestRestTemplateFactory.TEST_VAULT_ENDPOINT)
			.defaultHeader(VaultHttpHeaders.VAULT_NAMESPACE, "marketing");

	VaultTemplate dev = new VaultTemplate(this.devRestTemplate,
			new SimpleSessionManager(new TokenAuthentication(Settings.token())));

	mountKv(dev, "dev-secrets");
	dev.opsForSys().createOrUpdatePolicy("relaxed", POLICY);
	this.devToken = dev.opsForToken().create(VaultTokenRequest.builder().withPolicy("relaxed").build()).getToken()
			.getToken();

	VaultTemplate marketing = new VaultTemplate(this.maketingRestTemplate,
			new SimpleSessionManager(new TokenAuthentication(Settings.token())));

	mountKv(marketing, "marketing-secrets");
	marketing.opsForSys().createOrUpdatePolicy("relaxed", POLICY);
	this.marketingToken = marketing.opsForToken().create(VaultTokenRequest.builder().withPolicy("relaxed").build())
			.getToken().getToken();
}
 
Example 21
@Override
public ClientAuthentication clientAuthentication() {
	return new TokenAuthentication(Settings.token());
}
 
Example 22
/**
 * @return a new {@link ClientAuthentication}.
 */
ClientAuthentication createClientAuthentication() {

	switch (this.vaultProperties.getAuthentication()) {

	case APPID:
		return appIdAuthentication(this.vaultProperties);

	case APPROLE:
		return appRoleAuthentication(this.vaultProperties);

	case AWS_EC2:
		return awsEc2Authentication(this.vaultProperties);

	case AWS_IAM:
		return awsIamAuthentication(this.vaultProperties);

	case AZURE_MSI:
		return azureMsiAuthentication(this.vaultProperties);

	case CERT:
		return new ClientCertificateAuthentication(this.restOperations);

	case CUBBYHOLE:
		return cubbyholeAuthentication();

	case GCP_GCE:
		return gcpGceAuthentication(this.vaultProperties);

	case GCP_IAM:
		return gcpIamAuthentication(this.vaultProperties);

	case KUBERNETES:
		return kubernetesAuthentication(this.vaultProperties);

	case PCF:
		return pcfAuthentication(this.vaultProperties);

	case TOKEN:
		Assert.hasText(this.vaultProperties.getToken(),
				"Token (spring.cloud.vault.token) must not be empty");
		return new TokenAuthentication(this.vaultProperties.getToken());
	}

	throw new UnsupportedOperationException(
			String.format("Client authentication %s not supported",
					this.vaultProperties.getAuthentication()));
}
 
Example 23
/**
 * @param beanFactory the {@link BeanFactory}.
 * @return the {@link VaultTokenSupplier} for reactive Vault session management
 * adapting {@link ClientAuthentication} that also implement
 * {@link AuthenticationStepsFactory}.
 * @see AuthenticationStepsFactory
 */
@Bean
@ConditionalOnMissingBean(name = "vaultTokenSupplier")
@ConditionalOnAuthentication
public VaultTokenSupplier vaultTokenSupplier(ListableBeanFactory beanFactory) {

	Assert.notNull(beanFactory, "BeanFactory must not be null");

	String[] authStepsFactories = beanFactory
			.getBeanNamesForType(AuthenticationStepsFactory.class);

	if (!ObjectUtils.isEmpty(authStepsFactories)) {

		AuthenticationStepsFactory factory = beanFactory
				.getBean(AuthenticationStepsFactory.class);
		return createAuthenticationStepsOperator(factory);
	}

	String[] clientAuthentications = beanFactory
			.getBeanNamesForType(ClientAuthentication.class);

	if (!ObjectUtils.isEmpty(clientAuthentications)) {

		ClientAuthentication clientAuthentication = beanFactory
				.getBean(ClientAuthentication.class);

		if (clientAuthentication instanceof TokenAuthentication) {

			TokenAuthentication authentication = (TokenAuthentication) clientAuthentication;
			return () -> Mono.just(authentication.login());
		}

		if (clientAuthentication instanceof AuthenticationStepsFactory) {
			return createAuthenticationStepsOperator(
					(AuthenticationStepsFactory) clientAuthentication);
		}

		throw new IllegalStateException(String.format(
				"Cannot construct VaultTokenSupplier from %s. "
						+ "ClientAuthentication must implement AuthenticationStepsFactory or be TokenAuthentication",
				clientAuthentication));
	}

	throw new IllegalStateException(
			"Cannot construct VaultTokenSupplier. Please configure VaultTokenSupplier bean named vaultTokenSupplier.");
}
 
Example 24
@Override
public ClientAuthentication newInstance(AliasService localAliasService,
                                        Map<String, String> properties) throws Exception {
  String vaultToken = getVaultToken(localAliasService, properties);
  return new TokenAuthentication(vaultToken);
}
 
Example 25
Source Project: tutorials   Source File: VaultConfig.java    License: MIT License 4 votes vote down vote up
@Override
public ClientAuthentication clientAuthentication() {
    return new TokenAuthentication("00000000-0000-0000-0000-000000000000");
}
 
Example 26
ClientAuthentication configureClientAuthentication(KeyVaultConfig keyVaultConfig, EnvironmentVariableProvider envProvider, ClientHttpRequestFactory clientHttpRequestFactory, VaultEndpoint vaultEndpoint) {

        final String roleId = envProvider.getEnv(HASHICORP_ROLE_ID);
        final String secretId = envProvider.getEnv(HASHICORP_SECRET_ID);
        final String authToken = envProvider.getEnv(HASHICORP_TOKEN);

        if(roleId != null && secretId != null) {

            AppRoleAuthenticationOptions appRoleAuthenticationOptions = AppRoleAuthenticationOptions.builder()
                .path(keyVaultConfig.getProperty("approlePath").get())
                .roleId(AppRoleAuthenticationOptions.RoleId.provided(roleId))
                .secretId(AppRoleAuthenticationOptions.SecretId.provided(secretId))
                .build();

            RestOperations restOperations = VaultClients.createRestTemplate(vaultEndpoint, clientHttpRequestFactory);

            return new AppRoleAuthentication(appRoleAuthenticationOptions, restOperations);

        } else if (Objects.isNull(roleId) != Objects.isNull(secretId)) {

            throw new HashicorpCredentialNotSetException("Both " + HASHICORP_ROLE_ID + " and " + HASHICORP_SECRET_ID + " environment variables must be set to use the AppRole authentication method");

        } else if (authToken == null){

            throw new HashicorpCredentialNotSetException("Both " + HASHICORP_ROLE_ID + " and " + HASHICORP_SECRET_ID + " environment variables must be set to use the AppRole authentication method.  Alternatively set " + HASHICORP_TOKEN + " to authenticate using the Token method");
        }

        return new TokenAuthentication(authToken);
    }
 
Example 27
protected ClientAuthentication tokenAuthentication() {

		String token = getProperty("vault.token");
		Assert.hasText(token, "Vault Token authentication: Token (vault.token) must not be empty");

		return new TokenAuthentication(token);
	}