Java源码示例:org.springframework.vault.authentication.TokenAuthentication

示例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();
}
 
示例2
@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);
    }
}
 
示例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);
}
 
示例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));
}
 
示例5
@Test
void shouldConfigureTokenAuthentication() {

	ClientAuthentication clientAuthentication = this.configuration.clientAuthentication();

	assertThat(clientAuthentication).isInstanceOf(TokenAuthentication.class);
	assertThat(clientAuthentication.login()).isEqualTo(VaultToken.of("my-token"));
}
 
示例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();
}
 
示例7
@Test
void shouldReportInitialized() {

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

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

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

	assertThat(marketing.opsForSys().health().isInitialized()).isTrue();
}
 
示例9
@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();
}
 
示例10
@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);
}
 
示例11
@Override
public ClientAuthentication getClientAuthentication(
		VaultEnvironmentProperties vaultProperties,
		RestOperations vaultRestOperations, RestOperations externalRestOperations) {

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

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

	assertClientAuthenticationOfType(properties, TokenAuthentication.class);
}
 
示例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;
}
 
示例14
@Override
public ClientAuthentication clientAuthentication() {
    return new TokenAuthentication(vaultToken);
}
 
示例15
@Override
public ClientAuthentication clientAuthentication() {
	return new TokenAuthentication(getEnvironment().getProperty("vault.token"));
}
 
示例16
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");
	}
 
示例17
@Override
public ClientAuthentication clientAuthentication() {
	return new TokenAuthentication(Settings.token());
}
 
示例18
@Override
public ClientAuthentication clientAuthentication() {
	return new TokenAuthentication(Settings.token());
}
 
示例19
@Override
public ClientAuthentication clientAuthentication() {
	return new TokenAuthentication(Settings.token());
}
 
示例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();
}
 
示例21
@Override
public ClientAuthentication clientAuthentication() {
	return new TokenAuthentication(Settings.token());
}
 
示例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()));
}
 
示例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.");
}
 
示例24
@Override
public ClientAuthentication newInstance(AliasService localAliasService,
                                        Map<String, String> properties) throws Exception {
  String vaultToken = getVaultToken(localAliasService, properties);
  return new TokenAuthentication(vaultToken);
}
 
示例25
@Override
public ClientAuthentication clientAuthentication() {
    return new TokenAuthentication("00000000-0000-0000-0000-000000000000");
}
 
示例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);
    }
 
示例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);
	}