class Google.Apis.Auth.OAuth2.GoogleCredential.UnderlyingCredential.GetAccessTokenForRequestAsync() 等价于 Java?

class Google.Apis.Auth.OAuth2.GoogleCredential.UnderlyingCredential.GetAccessTokenForRequestAsync() equivalent in Java?

我已经用 C# 构建了一个 Azure Function App,我正在尝试找出 Google.Apis.Auth.OAuth2.GoogleCredential.UnderlyingCredential.GetAccessTokenForRequestAsync() 在 Java 中的等价物,因为我的客户需要我的代码框架要在 Java 中。我需要能够 return Json Web 令牌 (JWT) 并将其调用到函数内的 return 主体中。

我发现 Java class Google 凭证已贬值,但 Google 的一些产品文档仍然引用它:https://cloud.google.com/java/docs/reference/google-api-client/latest/com.google.api.client.googleapis.auth.oauth2.GoogleCredential .

下面是我用 C# 开发的代码片段,但我找不到任何类似的方式在 Java 中调用此 class:

using Google.Apis.Auth.OAuth2;

    var cred = GoogleCredential.FromJson(*[myjsonkey]*).CreateScoped(new string[] { "https://www.googleapis.com/auth/analytics.readonly" });
    var token = await cred.UnderlyingCredential.GetAccessTokenForRequestAsync();

Java class、Google凭证现在完全贬值(这里是 link:https://cloud.google.com/java/docs/reference/google-api-client/latest/com.google.api.client.googleapis.auth.oauth2.GoogleCredential#com_google_api_client_googleapis_auth_oauth2_GoogleCredential_createDelegated_java_lang_String_

任何关于我如何模仿 GoogleCredential class 等同于 Java 与 return JWT 的相同用法的任何建议或示例,我们将不胜感激。

更新:我现在明白 com.google.api.client.googleapis.auth.oauth2.GoogleCredential 的替代品现在是 com.google.auth.oauth2.GoogleCredentials,但我不知道如何使用它通过传入从 Azure Key Vault 调用的 json 密钥,这样我就可以 return JWT。这是我到目前为止构建的内容,调用 Azure Function 密钥保管库并 returning Google .json 与我的服务帐户关联的秘密文件。我收到一条 500 return 消息,因为我没有在响应中正确调用 JWT。我正在引用 this part of Google auth library for java 并且它不起作用。有什么技巧可以调整我的代码吗???

 package GetOAuthFunction;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.*;
import com.microsoft.azure.functions.annotation.*;
import com.microsoft.azure.functions.*;
import com.azure.security.keyvault.secrets.SecretClient;
import com.azure.security.keyvault.secrets.SecretClientBuilder;
import com.azure.security.keyvault.secrets.models.KeyVaultSecret;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.gson.*;

/**
 * Azure Functions with HTTP Trigger, getting value from Key Vault, returning Google Analytics Access Token in get request return body
 */
public class HttpKeyVaultFunc {
    @FunctionName("GetGoogleAnalyticsOAuthToken")
    public HttpResponseMessage run(
            @HttpTrigger(
                name = "req", 
                methods = {HttpMethod.GET}, 
                authLevel = AuthorizationLevel.ANONYMOUS) 
            HttpRequestMessage<Optional<String>> request,
            final ExecutionContext context) {
        context.getLogger().info("Java HTTP trigger processed a request.");

        String secret = System.getenv("KEY_VAULT_URL");
        SecretClient secretClient = new SecretClientBuilder()
        .vaultUrl(secret)
        .credential(new DefaultAzureCredentialBuilder().build())
        .buildClient();
        
        KeyVaultSecret retrievedSecret = secretClient.getSecret("clientsecret");
        
        String clientsecretvalue = retrievedSecret.getValue();
        JsonObject clientsecretarray = new Gson().fromJson(clientsecretvalue, JsonObject.class);
       GoogleCredentials credentials =  GoogleCredentials.fromStream(clientsecretarray).createScoped(new String {"https://www.googleapis.com/auth/analytics.readonly"}) ;
 
        return request.createResponseBuilder(HttpStatusOK).body("Access Token: "+ credentials.getAccessToken().build());
    }
}

尝试使用 HttpRequestInitializer。这是我在 Java.

中使用 Google Drive API 的示例代码
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.services.drive.Drive;
import com.google.auth.http.HttpCredentialsAdapter;

// file 1 is the JSON credential file
// GoogleCredential have been deprecated so instead I use HttpRequestInitializer 
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(ServiceAccountCredentials.fromStream(new FileInputStream(file1))
        .createScoped(DriveScopes.all()));
Drive drive = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
        .setApplicationName(ApplicationName).build();

这是来自 Google 文档说明的代码:

HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredential credential = GoogleCredential
        .fromStream(new FileInputStream(KEY_FILE_LOCATION))
        .createScoped(DriveScopes.all());

// Construct the drive service object.
return new Drive.Builder(httpTransport, JSON_FACTORY, credential)
        .setApplicationName(APPLICATION_NAME).build();

如您所料,Google Auth Library 包含针对 Google 服务进行身份验证所需的必要 类。

请在描述 Explicit credential loading 时考虑阅读 API 的文档:

To get Credentials from a Service Account JSON key use GoogleCredentials.fromStream(InputStream) or GoogleCredentials.fromStream(InputStream, HttpTransportFactory). Note that the credentials must be refreshed before the access token is available.

GoogleCredentials credentials = GoogleCredentials.fromStream(new 
FileInputStream("/path/to/credentials.json"));
credentials.refreshIfExpired();
AccessToken token = credentials.getAccessToken();
// OR
AccessToken token = credentials.refreshAccessToken();

在您的代码中,假设您的 Azure Key Vault 包含 JSON 格式的服务帐户凭据,您可以尝试如下操作:

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;
import com.microsoft.azure.functions.annotation.*;
import com.microsoft.azure.functions.*;
import com.azure.security.keyvault.secrets.SecretClient;
import com.azure.security.keyvault.secrets.SecretClientBuilder;
import com.azure.security.keyvault.secrets.models.KeyVaultSecret;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.gson.*;

/**
 * Azure Functions with HTTP Trigger, getting value from Key Vault, returning Google Analytics Access Token in get request return body
 */
public class HttpKeyVaultFunc {
    @FunctionName("GetGoogleAnalyticsOAuthToken")
    public HttpResponseMessage run(
            @HttpTrigger(
                name = "req", 
                methods = {HttpMethod.GET}, 
                authLevel = AuthorizationLevel.ANONYMOUS) 
            HttpRequestMessage<Optional<String>> request,
            final ExecutionContext context) {
        context.getLogger().info("Java HTTP trigger processed a request.");

        String secret = System.getenv("KEY_VAULT_URL");
        SecretClient secretClient = new SecretClientBuilder()
        .vaultUrl(secret)
        .credential(new DefaultAzureCredentialBuilder().build())
        .buildClient();
        
        KeyVaultSecret retrievedSecret = secretClient.getSecret("clientsecret");
        
        String clientSecretValue = retrievedSecret.getValue();
        byte[] clientSecretValueBytes = null;
        
        try {
            clientSecretValueBytes = clientSecretValue.getBytes("UTF-8");
        } catch (UnsupportedEncodingException use) {
            clientSecretValueBytes = clientSecretValue.getBytes();   
        }

        InputStream clientSecretValueStream = new ByteArrayInputStream(clientSecretValueBytes);

        GoogleCredentials credentials =  GoogleCredentials.fromStream(clientSecretValueStream)
            .createScoped("https://www.googleapis.com/auth/analytics.readonly") ;
        credentials.refreshIfExpired();
        AccessToken accessToken = credentials.getAccessToken();
 
        return request.createResponseBuilder(HttpStatusOK)
          .body("Access Token: " + accessToken.getTokenValue())
          .build();
    }
}