Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance. Project price only 1 $
You can buy this project and download/modify it how often you want.
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.security.keyvault.certificates.implementation;
import com.azure.core.credential.TokenCredential;
import com.azure.core.credential.TokenRequestContext;
import com.azure.core.http.HttpPipelineCallContext;
import com.azure.core.http.HttpPipelineNextPolicy;
import com.azure.core.http.HttpPipelineNextSyncPolicy;
import com.azure.core.http.HttpRequest;
import com.azure.core.http.HttpResponse;
import com.azure.core.http.policy.BearerTokenAuthenticationPolicy;
import com.azure.core.util.Base64Util;
import com.azure.core.util.BinaryData;
import com.azure.core.util.CoreUtils;
import com.azure.core.util.logging.ClientLogger;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static com.azure.core.http.HttpHeaderName.CONTENT_LENGTH;
import static com.azure.core.http.HttpHeaderName.WWW_AUTHENTICATE;
/**
* A policy that authenticates requests with the Azure Key Vault service. The content added by this policy is
* leveraged in {@link TokenCredential} to get and set the correct "Authorization" header value.
*
* @see TokenCredential
*/
public class KeyVaultCredentialPolicy extends BearerTokenAuthenticationPolicy {
private static final ClientLogger LOGGER = new ClientLogger(KeyVaultCredentialPolicy.class);
private static final String BEARER_TOKEN_PREFIX = "Bearer ";
private static final String KEY_VAULT_STASHED_CONTENT_KEY = "KeyVaultCredentialPolicyStashedBody";
private static final String KEY_VAULT_STASHED_CONTENT_LENGTH_KEY = "KeyVaultCredentialPolicyStashedContentLength";
private static final ConcurrentMap CHALLENGE_CACHE = new ConcurrentHashMap<>();
private ChallengeParameters challenge;
private final boolean disableChallengeResourceVerification;
/**
* Creates a {@link KeyVaultCredentialPolicy}.
*
* @param credential The token credential to authenticate the request.
*/
public KeyVaultCredentialPolicy(TokenCredential credential, boolean disableChallengeResourceVerification) {
super(credential);
this.disableChallengeResourceVerification = disableChallengeResourceVerification;
}
/**
* Extracts attributes off the bearer challenge in the authentication header.
*
* @param authenticateHeader The authentication header containing the challenge.
* @param authChallengePrefix The authentication challenge name.
*
* @return A challenge attributes map.
*/
private static Map extractChallengeAttributes(String authenticateHeader,
String authChallengePrefix) {
if (!isBearerChallenge(authenticateHeader, authChallengePrefix)) {
return Collections.emptyMap();
}
String[] attributes = authenticateHeader
.replace("\"", "")
.substring(authChallengePrefix.length())
.split(",");
Map attributeMap = new HashMap<>();
for (String pair : attributes) {
// Using trim is ugly, but we need it here because currently the 'claims' attribute comes after two spaces.
String[] keyValue = pair.trim().split("=", 2);
attributeMap.put(keyValue[0], keyValue[1]);
}
return attributeMap;
}
/**
* Verifies whether a challenge is bearer or not.
*
* @param authenticateHeader The authentication header containing all the challenges.
* @param authChallengePrefix The authentication challenge name.
*
* @return A boolean indicating if the challenge is a bearer challenge or not.
*/
private static boolean isBearerChallenge(String authenticateHeader, String authChallengePrefix) {
return (!CoreUtils.isNullOrEmpty(authenticateHeader)
&& authenticateHeader.toLowerCase(Locale.ROOT).startsWith(authChallengePrefix.toLowerCase(Locale.ROOT)));
}
@Override
public Mono authorizeRequest(HttpPipelineCallContext context) {
return Mono.defer(() -> {
HttpRequest request = context.getHttpRequest();
// If this policy doesn't have challenge parameters cached try to get it from the static challenge cache.
if (this.challenge == null) {
this.challenge = CHALLENGE_CACHE.get(getRequestAuthority(request));
}
if (this.challenge != null) {
// We fetched the challenge from the cache, but we have not initialized the scopes in the base yet.
TokenRequestContext tokenRequestContext = new TokenRequestContext()
.addScopes(this.challenge.getScopes())
.setTenantId(this.challenge.getTenantId())
.setCaeEnabled(true);
return setAuthorizationHeader(context, tokenRequestContext);
}
// The body is removed from the initial request because Key Vault supports other authentication schemes
// which also protect the body of the request. As a result, before we know the auth scheme we need to
// avoid sending an unprotected body to Key Vault. We don't currently support this enhanced auth scheme
// in the SDK, but we still don't want to send any unprotected data to vaults which require it.
// Do not overwrite previous contents if retrying after initial request failed (e.g. timeout).
if (!context.getData(KEY_VAULT_STASHED_CONTENT_KEY).isPresent()) {
if (request.getBody() != null) {
context.setData(KEY_VAULT_STASHED_CONTENT_KEY, request.getBody());
context.setData(KEY_VAULT_STASHED_CONTENT_LENGTH_KEY,
request.getHeaders().getValue(CONTENT_LENGTH));
request.setHeader(CONTENT_LENGTH, "0");
request.setBody((Flux) null);
}
}
return Mono.empty();
});
}
@SuppressWarnings("unchecked")
@Override
public Mono authorizeRequestOnChallenge(HttpPipelineCallContext context, HttpResponse response) {
return Mono.defer(() -> {
HttpRequest request = context.getHttpRequest();
Optional