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

发布于 2025-01-20 15:58:08 字数 601 浏览 0 评论 0原文

我使用 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

谢谢!

I am using Microsoft Graph SDK for some requests however everytime I perform a GET request it does another request to get a token. I've tried reading documentation about this but I cannot find anything in Java.

Here is my implementation of my client

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

I have also tried using the method .tokenCachePersistenceOptions() in my builder but I get this warning/error

c.m.a.m.CrossProcessCacheFileLock        : null

Thank you!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

渡你暖光 2025-01-27 15:58:08

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

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

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

To achieve the above requirement Firstly you need to Authenticate for implementing MSAL to get the token from Azure AD.

To obtain an access token, your app must be registered with the Microsoft identity platform and approved to access the Microsoft Graph resources it requires by either a user who is added as an owner for that application or an administrator.

For complete setup please refer this MS DOCUMENT Authentication and authorization basics for Microsoft Graph , This sample & GitHub sample|msgraph-sdk-java-core

如此安好 2025-01-27 15:58:08

我一直在寻找相同的思考,这是我为此实施的:

实现您自己的身份验证提供商类:

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 401 < /em>您应该更新您的令牌。

当您成功登录客户时,您可以通过以下方式获得令牌:

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()

希望这会有所帮助。

I was looking for the same think and here's what I've implemented for it:

Implement your own authentication provider 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);
    }
}

Then you can use it as follow:

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();

If you get an GraphServiceException code 401 you should renew your token.

When you are successfully logged in with your clientSecretCredential, here's how you can get the token:

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()

Hope this helps.

复古式 2025-01-27 15:58:08

您可以覆盖为GraphServiceClient提供的Authentication Provider,

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;
    }
}

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

You can override the authenticationProvider which is provided for the GraphServiceClient

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;
    }
}

This will cache the token until it one minute before it is no longer valid.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文