com.azure.identity.AuthenticationUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of azure-identity Show documentation
Show all versions of azure-identity Show documentation
This module contains client library for Microsoft Azure Identity.
The newest version!
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.identity;
import com.azure.core.credential.TokenCredential;
import com.azure.core.http.HttpHeaderName;
import com.azure.core.http.HttpMethod;
import com.azure.core.http.HttpPipeline;
import com.azure.core.http.HttpPipelineBuilder;
import com.azure.core.http.HttpRequest;
import com.azure.core.http.HttpResponse;
import com.azure.core.http.policy.BearerTokenAuthenticationPolicy;
import com.azure.core.util.Context;
import java.util.function.Supplier;
/**
* Utility methods for working with authentication.
*/
public final class AuthenticationUtil {
private AuthenticationUtil() {
}
/**
* Creates a {@link Supplier} that provides a Bearer token from the specified credential.
* The token is cached and will refresh when it expires.
* Using the supplier:
*
*
* DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build();
* String scope = "https://cognitiveservices.azure.com/.default";
* Supplier<String> supplier = AuthenticationUtil.getBearerTokenSupplier(credential, scope);
*
* // This example simply uses the Azure SDK HTTP library to demonstrate setting the header.
* // Use the token as is appropriate for your circumstances.
* HttpRequest request = new HttpRequest(HttpMethod.GET, "https://www.example.com");
* request.setHeader(HttpHeaderName.AUTHORIZATION, "Bearer " + supplier.get());
* HttpClient client = HttpClient.createDefault();
* client.sendSync(request, Context.NONE);
*
*
*
* @param credential The {@link TokenCredential} from which to retrieve a token.
* @param scopes The scopes as appropriate for the token you are retrieving.
* @return A {@link Supplier} which returns the bearer token as a {@link String}.
*/
public static Supplier getBearerTokenSupplier(TokenCredential credential, String... scopes) {
HttpPipeline pipeline
= new HttpPipelineBuilder().policies(new BearerTokenAuthenticationPolicy(credential, scopes)).build();
return () -> {
// This request will never need to go anywhere; it is simply to cause the policy to interact with
// the user's credential
HttpRequest req = new HttpRequest(HttpMethod.GET, "https://www.example.com");
try (HttpResponse res = pipeline.sendSync(req, Context.NONE)) {
return res.getRequest().getHeaders().get(HttpHeaderName.AUTHORIZATION).getValue().split(" ")[1];
}
};
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy