繁体   English   中英

如何使用 Microsoft Graph 为 Java 缓存令牌

[英]How to cache token with Microsoft Graph for Java

我正在为某些请求使用 Microsoft Graph SDK,但是每次我执行 GET 请求时,它都会执行另一个请求来获取令牌。 我试过阅读有关此的文档,但在 Java 中找不到任何内容。

这是我对客户的实现

         ClientSecretCredential clientSecretCredential = new ClientSecretCredentialBuilder()
            .clientId(clientId)
            .clientSecret(clientSecret)
            .tenantId(tenantId)
            .httpClient(httpClient)
            .build();

我也尝试在我的构建器中使用方法.tokenCachePersistenceOptions()但我收到此警告/错误

c.m.a.m.CrossProcessCacheFileLock        : null

谢谢!

要实现上述要求,首先您需要进行身份验证以实现 MSAL 以从 Azure AD 获取令牌

要获取访问令牌,你的应用必须在 Microsoft 标识平台上注册,并由添加为该应用程序所有者的用户或管理员批准访问它所需的 Microsoft Graph 资源。

有关完整设置,请参阅此 MS 文档Microsoft Graph 身份验证和授权基础知识此示例GitHub 示例|msgraph-sdk-java-core

我一直在寻找相同的想法,这是我为它实现的:

实施您自己的身份验证提供程序 class:

public class DelegateAuthenticationProvider implements IAuthenticationProvider {
    private String token;

    public DelegateAuthenticationProvider(String token) {
        this.token = token;
    }

    @NotNull
    @Override
    public CompletableFuture<String> getAuthorizationTokenAsync(@NotNull URL url) {
        return CompletableFuture.completedFuture(token);
    }
}

然后你可以按如下方式使用它:

String token = "<YOUR_TOKEN_STRING>"
IAuthenticationProvider tokenCredentialAuthProvider = new DelegateAuthenticationProvider(token);

// Create the Graph Client with the given Token Provider
GraphServiceClient graphClient = GraphServiceClient.builder()
        .authenticationProvider(tokenCredentialAuthProvider)
        .buildClient();

如果您收到GraphServiceException代码401 ,您应该更新您的令牌。

当您使用 clientSecretCredential 成功登录后,您可以通过以下方式获取令牌:

List<String> scopes = Arrays.asList("https://graph.microsoft.com/.default");
IAuthenticationProvider tokenCredentialAuthProvider = new TokenCredentialAuthProvider(scopes, clientSecretCredential);
String token = tokenCredentialAuthProvider.getAuthorizationTokenAsync("https://graph.microsoft.com/v1.0/me").get()

希望这可以帮助。

您可以覆盖为 GraphServiceClient 提供的 authenticationProvider

import com.azure.core.credential.AccessToken;
import com.azure.core.credential.TokenCredential;
import com.azure.core.credential.TokenRequestContext;
import com.microsoft.graph.authentication.TokenCredentialAuthProvider;
import org.jetbrains.annotations.NotNull;

import java.net.URL;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;

public class CachingTokenCredentialAuthProvider extends TokenCredentialAuthProvider {
    private final TokenCredential tokenCredential;
    private final TokenRequestContext context;
    private AccessToken accessToken;

    public CachingTokenCredentialAuthProvider(@NotNull List<String> scopes, @NotNull TokenCredential tokenCredential) {
        super(scopes, tokenCredential);
        if (!scopes.isEmpty()) {
            this.context = new TokenRequestContext();
            this.context.setScopes(scopes);
            this.tokenCredential = Objects.requireNonNull(tokenCredential, "tokenCredential parameter cannot be null.");
        } else {
            throw new IllegalArgumentException("scopes parameter cannot be null or empty");
        }
    }

    @NotNull
    @Override
    public CompletableFuture<String> getAuthorizationTokenAsync(@NotNull URL requestUrl) {
        if (this.shouldAuthenticateRequestWithUrl(Objects.requireNonNull(requestUrl, "requestUrl parameter cannot be null"))) {
            if(this.accessToken != null && !OffsetDateTime.now().minusMinutes(1).isAfter(this.accessToken.getExpiresAt())) {
                return CompletableFuture.completedFuture(this.accessToken.getToken());
            }

            return this.tokenCredential.getToken(this.context).toFuture().thenApply(accessToken -> {
                saveToken(accessToken);
                return accessToken.getToken();
            });
        } else {
            return CompletableFuture.completedFuture(null);
        }
    }

    void saveToken(AccessToken accessToken) {
        this.accessToken = accessToken;
    }
}

这将缓存令牌,直到它不再有效前一分钟。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM