org.springframework.vault.support.VaultToken Java Examples
The following examples show how to use
org.springframework.vault.support.VaultToken.
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
Source File: ReactiveLifecycleAwareSessionManager.java From spring-vault with Apache License 2.0 | 8 votes |
/** * Performs a token refresh. Creates a new token if no token was obtained before. If a * token was obtained before, it uses self-renewal to renew the current token. * Client-side errors (like permission denied) indicate the token cannot be renewed * because it's expired or simply not found. * @return the {@link VaultToken} if the refresh was successful or a new token was * obtained. {@link Mono#empty()} if a new the token expired or * {@link Mono#error(Throwable)} if refresh failed. */ public Mono<VaultToken> renewToken() { this.logger.info("Renewing token"); Mono<TokenWrapper> tokenWrapper = this.token.get(); if (tokenWrapper == TERMINATED) { return tokenWrapper.map(TokenWrapper::getToken); } if (tokenWrapper == EMPTY) { return getVaultToken(); } return tokenWrapper.flatMap(this::doRenewToken).map(TokenWrapper::getToken); }
Example #2
Source File: VaultNamespaceTests.java From spring-cloud-vault with Apache License 2.0 | 7 votes |
@Test public void shouldReportReactiveHealth() { ReactiveVaultTemplate reactiveMarketing = new ReactiveVaultTemplate( this.marketingWebClientBuilder, () -> Mono.just(VaultToken.of(this.marketingToken))); Health.Builder builder = Health.unknown(); new VaultReactiveHealthIndicator(reactiveMarketing).doHealthCheck(builder) .as(StepVerifier::create) .assertNext(actual -> assertThat(actual.getStatus()).isEqualTo(Status.UP)) .verifyComplete(); }
Example #3
Source File: PcfAuthenticationUnitTests.java From spring-vault with Apache License 2.0 | 6 votes |
@Test void loginShouldObtainToken() { PcfAuthenticationOptions options = PcfAuthenticationOptions.builder().instanceCertificate(() -> "foo") // .instanceKey(() -> this.instanceKey) // .role("dev-role") // .clock(this.clock) // .build(); PcfAuthentication authentication = new PcfAuthentication(options, this.restTemplate); expectLoginRequest(); VaultToken login = authentication.login(); assertThat(login).isInstanceOf(LoginToken.class); assertThat(login.getToken()).isEqualTo("my-token"); }
Example #4
Source File: ClientCertificateAuthenticationUnitTests.java From spring-vault with Apache License 2.0 | 6 votes |
@Test void loginShouldObtainToken() { this.mockRest.expect(requestTo("/auth/my/path/login")).andExpect(method(HttpMethod.POST)) .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body( "{" + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}" + "}")); ClientCertificateAuthenticationOptions options = ClientCertificateAuthenticationOptions.builder() .path("my/path").build(); ClientCertificateAuthentication sut = new ClientCertificateAuthentication(options, this.restTemplate); VaultToken login = sut.login(); assertThat(login).isInstanceOf(LoginToken.class); assertThat(login.getToken()).isEqualTo("my-token"); assertThat(((LoginToken) login).getLeaseDuration()).isEqualTo(Duration.ofSeconds(10)); assertThat(((LoginToken) login).isRenewable()).isTrue(); }
Example #5
Source File: AppRoleAuthentication.java From spring-vault with Apache License 2.0 | 6 votes |
private VaultToken createTokenUsingAppRole() { Map<String, String> login = getAppRoleLoginBody(this.options.getRoleId(), this.options.getSecretId()); try { VaultResponse response = this.restOperations.postForObject(getLoginPath(this.options.getPath()), login, VaultResponse.class); Assert.state(response != null && response.getAuth() != null, "Auth field must not be null"); logger.debug("Login successful using AppRole authentication"); return LoginTokenUtil.from(response.getAuth()); } catch (RestClientException e) { throw VaultLoginException.create("AppRole", e); } }
Example #6
Source File: ReactiveLifecycleAwareSessionManagerUnitTests.java From spring-vault with Apache License 2.0 | 6 votes |
@Test @SuppressWarnings("unchecked") void shouldContinueIfSelfLookupFails() { VaultResponse vaultResponse = new VaultResponse(); vaultResponse.setData(Collections.singletonMap("ttl", 100)); mockToken(VaultToken.of("login")); when(this.responseSpec.bodyToMono((Class) any())).thenReturn( Mono.error(new WebClientResponseException("forbidden", 403, "Forbidden", null, null, null))); this.sessionManager.getSessionToken() // .as(StepVerifier::create) // .assertNext(it -> { assertThat(it).isExactlyInstanceOf(VaultToken.class); }).verifyComplete(); verify(this.listener).onAuthenticationEvent(any(AfterLoginEvent.class)); verify(this.errorListener).onAuthenticationError(any()); }
Example #7
Source File: ReactiveLifecycleAwareSessionManager.java From spring-vault with Apache License 2.0 | 6 votes |
/** * Revoke a {@link VaultToken}. * @param token the token to revoke, must not be {@literal null}. */ protected Mono<Void> revoke(VaultToken token) { return this.webClient.post().uri("auth/token/revoke-self").headers(httpHeaders -> { httpHeaders.addAll(VaultHttpHeaders.from(token)); }).retrieve().bodyToMono(String.class) .doOnSubscribe(ignore -> dispatch(new BeforeLoginTokenRevocationEvent(token))) .doOnNext(ignore -> dispatch(new AfterLoginTokenRevocationEvent(token))) .onErrorResume(WebClientResponseException.class, e -> { this.logger.warn(format("Could not revoke token", e)); dispatch(new LoginTokenRevocationFailedEvent(token, e)); return Mono.empty(); }).onErrorResume(Exception.class, e -> { this.logger.warn("Could not revoke token", e); dispatch(new LoginTokenRevocationFailedEvent(token, e)); return Mono.empty(); }).then(); }
Example #8
Source File: AuthenticationStepsOperatorUnitTests.java From spring-vault with Apache License 2.0 | 6 votes |
@Test void justLoginRequestShouldLogin() { ClientHttpRequest request = new MockClientHttpRequest(HttpMethod.POST, "/auth/cert/login"); MockClientHttpResponse response = new MockClientHttpResponse(HttpStatus.OK); response.getHeaders().setContentType(MediaType.APPLICATION_JSON); response.setBody( "{" + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}" + "}"); ClientHttpConnector connector = (method, uri, fn) -> fn.apply(request).then(Mono.just(response)); WebClient webClient = WebClient.builder().clientConnector(connector).build(); AuthenticationSteps steps = AuthenticationSteps .just(post("/auth/{path}/login", "cert").as(VaultResponse.class)); login(steps, webClient).as(StepVerifier::create) // .expectNext(VaultToken.of("my-token")) // .verifyComplete(); }
Example #9
Source File: ClientAuthenticationFactoryUnitTests.java From spring-cloud-vault with Apache License 2.0 | 6 votes |
@Test public void shouldSupportAppRoleFullPull() { VaultProperties properties = new VaultProperties(); properties.setToken("token"); properties.getAppRole().setRole("my-role"); AppRoleAuthenticationOptions options = ClientAuthenticationFactory .getAppRoleAuthenticationOptions(properties); assertThat(options.getAppRole()).isEqualTo("my-role"); assertThat(options.getRoleId()) .isInstanceOf(RoleId.pull(VaultToken.of("token")).getClass()); assertThat(options.getSecretId()) .isInstanceOf(SecretId.pull(VaultToken.of("token")).getClass()); }
Example #10
Source File: AppIdAuthentication.java From spring-vault with Apache License 2.0 | 6 votes |
private VaultToken createTokenUsingAppId() { Map<String, String> login = getAppIdLogin(this.options.getAppId(), this.options.getUserIdMechanism().createUserId()); try { VaultResponse response = this.restOperations .postForObject(AuthenticationUtil.getLoginPath(this.options.getPath()), login, VaultResponse.class); Assert.state(response != null && response.getAuth() != null, "Auth field must not be null"); logger.debug("Login successful using AppId authentication"); return LoginTokenUtil.from(response.getAuth()); } catch (RestClientException e) { throw VaultLoginException.create("app-id", e); } }
Example #11
Source File: AzureMsiAuthenticationUnitTests.java From spring-vault with Apache License 2.0 | 6 votes |
@Test void loginWithStepsShouldObtainTokenAndFetchMetadata() { AzureMsiAuthenticationOptions options = AzureMsiAuthenticationOptions.builder().role("dev-role") // .build(); expectMetadataRequest(); expectIdentityTokenRequest(); expectLoginRequest(); AuthenticationStepsExecutor authentication = new AuthenticationStepsExecutor( AzureMsiAuthentication.createAuthenticationSteps(options), this.restTemplate); VaultToken login = authentication.login(); assertThat(login).isInstanceOf(LoginToken.class); assertThat(login.getToken()).isEqualTo("my-token"); }
Example #12
Source File: CubbyholeAuthenticationUnitTests.java From spring-vault with Apache License 2.0 | 6 votes |
@Test void shouldLoginUsingStoredLogin() { this.mockRest.expect(requestTo("/cubbyhole/token")).andExpect(method(HttpMethod.GET)) .andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "hello")) .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON) .body("{\"data\":{\"mytoken\":\"058222ef-9ab9-ff39-f087-9d5bee64e46d\"} }")); CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder() .initialToken(VaultToken.of("hello")).path("cubbyhole/token").selfLookup(false).build(); CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, this.restTemplate); VaultToken login = authentication.login(); assertThat(login).isNotInstanceOf(LoginToken.class); assertThat(login.getToken()).isEqualTo("058222ef-9ab9-ff39-f087-9d5bee64e46d"); }
Example #13
Source File: AppRoleClientAuthenticationProvider.java From spring-cloud-config with Apache License 2.0 | 6 votes |
private static AppRoleAuthenticationOptions.RoleId getRoleId( VaultEnvironmentProperties vaultProperties, VaultEnvironmentProperties.AppRoleProperties appRole) { if (StringUtils.hasText(appRole.getRoleId())) { return AppRoleAuthenticationOptions.RoleId.provided(appRole.getRoleId()); } if (StringUtils.hasText(vaultProperties.getToken()) && StringUtils.hasText(appRole.getRole())) { return AppRoleAuthenticationOptions.RoleId .pull(VaultToken.of(vaultProperties.getToken())); } if (StringUtils.hasText(vaultProperties.getToken())) { return AppRoleAuthenticationOptions.RoleId .wrapped(VaultToken.of(vaultProperties.getToken())); } throw new IllegalArgumentException("Any of '" + VAULT_PROPERTIES_PREFIX + "app-role.role-id', '.token', " + "or '.app-role.role' and '.token' must be provided if the " + AuthenticationMethod.APPROLE + " authentication method is specified."); }
Example #14
Source File: VaultWrappingTemplate.java From spring-vault with Apache License 2.0 | 6 votes |
@Nullable private <T extends VaultResponseSupport<?>> T doUnwrap(VaultToken token, BiFunction<RestOperations, HttpEntity<?>, T> requestFunction) { return this.vaultOperations.doWithVault(restOperations -> { try { return requestFunction.apply(restOperations, new HttpEntity<>(VaultHttpHeaders.from(token))); } catch (HttpStatusCodeException e) { if (e.getStatusCode() == HttpStatus.NOT_FOUND) { return null; } if (e.getStatusCode() == HttpStatus.BAD_REQUEST && e.getResponseBodyAsString().contains("does not exist")) { return null; } throw VaultResponses.buildException(e, "sys/wrapping/unwrap"); } }); }
Example #15
Source File: AuthenticationStepsExecutorUnitTests.java From spring-vault with Apache License 2.0 | 6 votes |
@Test void initialRequestWithMapShouldLogin() { this.mockRest.expect(requestTo("somewhere/else")).andExpect(method(HttpMethod.GET)) .andRespond(withSuccess().contentType(MediaType.TEXT_PLAIN).body("foo")); this.mockRest.expect(requestTo("/auth/cert/login")).andExpect(method(HttpMethod.POST)) .andExpect(content().string("foo-token")) .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body( "{" + "\"auth\":{\"client_token\":\"foo-token\", \"renewable\": true, \"lease_duration\": 10}" + "}")); AuthenticationSteps steps = AuthenticationSteps .fromHttpRequest(get(URI.create("somewhere/else")).as(String.class)).onNext(System.out::println) // .map(s -> s.concat("-token")) // .login("/auth/cert/login"); assertThat(login(steps)).isEqualTo(VaultToken.of("foo-token")); }
Example #16
Source File: PcfAuthenticationUnitTests.java From spring-vault with Apache License 2.0 | 6 votes |
@Test void loginWithStepsShouldObtainToken() { PcfAuthenticationOptions options = PcfAuthenticationOptions.builder().instanceCertificate(() -> "foo") // .instanceKey(() -> this.instanceKey) // .role("dev-role") // .clock(this.clock) // .build(); expectLoginRequest(); AuthenticationStepsExecutor authentication = new AuthenticationStepsExecutor( PcfAuthentication.createAuthenticationSteps(options), this.restTemplate); VaultToken login = authentication.login(); assertThat(login).isInstanceOf(LoginToken.class); assertThat(login.getToken()).isEqualTo("my-token"); }
Example #17
Source File: AwsEc2AuthenticationUnitTests.java From spring-vault with Apache License 2.0 | 6 votes |
@Test void shouldLogin() { Nonce nonce = Nonce.provided("foo".toCharArray()); AwsEc2AuthenticationOptions authenticationOptions = AwsEc2AuthenticationOptions.builder().nonce(nonce).build(); this.mockRest.expect(requestTo("http://169.254.169.254/latest/dynamic/instance-identity/pkcs7")) // .andExpect(method(HttpMethod.GET)) // .andRespond(withSuccess().body("value")); this.mockRest.expect(requestTo("/auth/aws-ec2/login")).andExpect(method(HttpMethod.POST)) .andExpect(jsonPath("$.pkcs7").value("value")).andExpect(jsonPath("$.nonce").value("foo")) .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON) .body("{" + "\"auth\":{\"client_token\":\"my-token\", \"lease_duration\":20}" + "}")); AwsEc2Authentication authentication = new AwsEc2Authentication(authenticationOptions, this.restTemplate, this.restTemplate); VaultToken login = authentication.login(); assertThat(login).isInstanceOf(LoginToken.class); assertThat(login.getToken()).isEqualTo("my-token"); assertThat(((LoginToken) login).getLeaseDuration()).isEqualTo(Duration.ofSeconds(20)); assertThat(((LoginToken) login).isRenewable()).isFalse(); }
Example #18
Source File: AppRoleClientAuthenticationProviderTests.java From spring-cloud-config with Apache License 2.0 | 6 votes |
@Test public void appRoleWithFullPull() { VaultEnvironmentProperties properties = new VaultEnvironmentProperties(); properties.setToken("token"); properties.getAppRole().setRole("my-role"); AppRoleAuthenticationOptions options = AppRoleClientAuthenticationProvider .getAppRoleAuthenticationOptions(properties); assertThat(options.getAppRole()).isEqualTo("my-role"); assertThat(options.getRoleId()) .isInstanceOf(RoleId.pull(VaultToken.of("token")).getClass()); assertThat(options.getSecretId()) .isInstanceOf(SecretId.pull(VaultToken.of("token")).getClass()); }
Example #19
Source File: CubbyholeAuthentication.java From spring-vault with Apache License 2.0 | 6 votes |
@Override public VaultToken login() throws VaultException { String url = getRequestPath(this.options); VaultResponse data = lookupToken(url); VaultToken tokenToUse = getToken(this.options, data, url); if (shouldEnhanceTokenWithSelfLookup(tokenToUse)) { LoginTokenAdapter adapter = new LoginTokenAdapter(new TokenAuthentication(tokenToUse), this.restOperations); tokenToUse = adapter.login(); } logger.debug("Login successful using Cubbyhole authentication"); return tokenToUse; }
Example #20
Source File: TokenAuthenticationOperatorIntegrationTests.java From spring-vault with Apache License 2.0 | 6 votes |
@Test void shouldFailDuringSelfLookup() { VaultTokenRequest tokenRequest = VaultTokenRequest.builder().ttl(Duration.ofSeconds(60)).renewable().numUses(1) .build(); VaultToken token = prepare().getVaultOperations().opsForToken().create(tokenRequest).getToken(); AuthenticationStepsOperator operator = new AuthenticationStepsOperator( TokenAuthentication.createAuthenticationSteps(token, true), this.webClient); // first usage operator.getVaultToken() // .as(StepVerifier::create) // .expectNextCount(1) // .verifyComplete(); operator.getVaultToken() // .as(StepVerifier::create) // .expectError(VaultException.class) // .verify(); }
Example #21
Source File: CubbyholeAuthentication.java From spring-vault with Apache License 2.0 | 6 votes |
private static VaultToken getToken(CubbyholeAuthenticationOptions options, VaultResponse response, String url) { if (options.isWrappedToken()) { VaultResponse responseToUse = options.getUnwrappingEndpoints().unwrap(response); Assert.state(responseToUse.getAuth() != null, "Auth field must not be null"); return LoginTokenUtil.from(responseToUse.getAuth()); } Map<String, Object> data = response.getData(); if (data == null || data.isEmpty()) { throw new VaultLoginException( String.format("Cannot retrieve Token from Cubbyhole: Response at %s does not contain a token", options.getPath())); } if (data.size() == 1) { String token = (String) data.get(data.keySet().iterator().next()); return VaultToken.of(token); } throw new VaultLoginException(String .format("Cannot retrieve Token from Cubbyhole: Response at %s does not contain an unique token", url)); }
Example #22
Source File: ClientAuthenticationFactory.java From spring-cloud-vault with Apache License 2.0 | 6 votes |
private static SecretId getSecretId(VaultProperties vaultProperties, AppRoleProperties appRole) { if (StringUtils.hasText(appRole.getSecretId())) { return SecretId.provided(appRole.getSecretId()); } if (StringUtils.hasText(vaultProperties.getToken()) && StringUtils.hasText(appRole.getRole())) { return SecretId.pull(VaultToken.of(vaultProperties.getToken())); } if (StringUtils.hasText(vaultProperties.getToken())) { return SecretId.wrapped(VaultToken.of(vaultProperties.getToken())); } return SecretId.absent(); }
Example #23
Source File: TokenAuthenticationStepsIntegrationTests.java From spring-vault with Apache License 2.0 | 5 votes |
@Test void shouldFailDuringSelfLookup() { VaultTokenRequest tokenRequest = VaultTokenRequest.builder().ttl(Duration.ofSeconds(60)).renewable().numUses(1) .build(); VaultToken token = prepare().getVaultOperations().opsForToken().create(tokenRequest).getToken(); AuthenticationStepsExecutor operator = new AuthenticationStepsExecutor( TokenAuthentication.createAuthenticationSteps(token, true), this.restTemplate); operator.login(); assertThatExceptionOfType(VaultException.class).isThrownBy(operator::login); }
Example #24
Source File: AuthenticationStepsExecutorUnitTests.java From spring-vault with Apache License 2.0 | 5 votes |
@Test void justLoginRequestShouldLogin() { this.mockRest.expect(requestTo("/auth/cert/login")).andExpect(method(HttpMethod.POST)) .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body( "{" + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}" + "}")); AuthenticationSteps steps = AuthenticationSteps .just(post("/auth/{path}/login", "cert").as(VaultResponse.class)); assertThat(login(steps)).isEqualTo(VaultToken.of("my-token")); }
Example #25
Source File: AppRoleAuthentication.java From spring-vault with Apache License 2.0 | 5 votes |
private static Node<VaultResponse> unwrapResponse(UnwrappingEndpoints unwrappingEndpoints, VaultToken token) { return AuthenticationSteps .fromHttpRequest(method(unwrappingEndpoints.getUnwrapRequestMethod(), unwrappingEndpoints.getPath()) .with(createHttpHeaders(token)).as(VaultResponse.class)) .map(unwrappingEndpoints::unwrap); }
Example #26
Source File: ReactiveLifecycleAwareSessionManagerIntegrationTests.java From spring-vault with Apache License 2.0 | 5 votes |
@Test void shouldRevokeOnDisposal() { final LoginToken loginToken = createLoginToken(); ReactiveLifecycleAwareSessionManager sessionManager = new ReactiveLifecycleAwareSessionManager( () -> Flux.fromStream(Stream.of((VaultToken) loginToken)).next(), this.taskScheduler, prepare().getWebClient()); sessionManager.getSessionToken() // .as(StepVerifier::create) // .expectNext(loginToken) // .verifyComplete(); sessionManager.destroy(); prepare().getVaultOperations().doWithSession(restOperations -> { try { restOperations.getForEntity("auth/token/lookup/{token}", Map.class, loginToken.toCharArray()); fail("Missing HttpStatusCodeException"); } catch (HttpStatusCodeException e) { // Compatibility across Vault versions. assertThat(e.getStatusCode()).isIn(HttpStatus.BAD_REQUEST, HttpStatus.NOT_FOUND, HttpStatus.FORBIDDEN); } return null; }); }
Example #27
Source File: AppRoleClientAuthenticationProviderTests.java From spring-cloud-config with Apache License 2.0 | 5 votes |
@Test public void appRoleFullWrapped() { VaultEnvironmentProperties properties = new VaultEnvironmentProperties(); properties.setToken("token"); AppRoleAuthenticationOptions options = AppRoleClientAuthenticationProvider .getAppRoleAuthenticationOptions(properties); assertThat(options.getRoleId()) .isInstanceOf(RoleId.wrapped(VaultToken.of("token")).getClass()); assertThat(options.getSecretId()) .isInstanceOf(SecretId.wrapped(VaultToken.of("token")).getClass()); }
Example #28
Source File: AppRoleAuthenticationStepsIntegrationTests.java From spring-vault with Apache License 2.0 | 5 votes |
@Test void authenticationStepsShouldAuthenticateWithWrappedSecretId() { String roleId = getRoleId("with-secret-id"); VaultToken unwrappingToken = generateWrappedSecretIdResponse(); AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() .secretId(SecretId.wrapped(unwrappingToken)).roleId(RoleId.provided(roleId)) .unwrappingEndpoints(getUnwrappingEndpoints()).build(); AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor( AppRoleAuthentication.createAuthenticationSteps(options), prepare().getRestTemplate()); assertThat(executor.login()).isNotNull(); }
Example #29
Source File: AuthenticationStepsOperatorUnitTests.java From spring-vault with Apache License 2.0 | 5 votes |
@Test void justTokenShouldLogin() { AuthenticationSteps steps = AuthenticationSteps.just(VaultToken.of("my-token")); login(steps).as(StepVerifier::create) // .expectNext(VaultToken.of("my-token")) // .verifyComplete(); }
Example #30
Source File: ClientAuthenticationFactoryUnitTests.java From spring-cloud-vault with Apache License 2.0 | 5 votes |
@Test public void shouldSupportAppRoleRoleIdWrappedSecretIdProvided() { VaultProperties properties = new VaultProperties(); properties.setToken("token"); properties.getAppRole().setSecretId("bar"); AppRoleAuthenticationOptions options = ClientAuthenticationFactory .getAppRoleAuthenticationOptions(properties); assertThat(options.getRoleId()) .isInstanceOf(RoleId.wrapped(VaultToken.of("token")).getClass()); assertThat(options.getSecretId()) .isInstanceOf(SecretId.provided("bar").getClass()); }