You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Azure AD SDK Java的AccessToken复用及Graph API调用问题咨询

Azure AD Java SDK 令牌使用与Graph API调用指南

背景

已通过ClientSecretCredential获取AccessToken,需解决令牌调用API、GraphClient集成、令牌过期验证与刷新的问题。

1. 使用令牌直接调用用户/组接口

直接调用Microsoft Graph API时,需在HTTP请求头中携带Authorization: Bearer {accessToken},示例如下:

示例:用Java HttpClient调用获取用户列表

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class GraphApiCaller {
    public static void getUsers(String accessToken) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://graph.microsoft.com/v1.0/users"))
                .header("Authorization", "Bearer " + accessToken)
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }

    // 调用组列表接口逻辑类似
    public static void getGroups(String accessToken) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://graph.microsoft.com/v1.0/groups"))
                .header("Authorization", "Bearer " + accessToken)
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

2. 通过令牌获取GraphClient调用API

可以使用Microsoft Graph Java SDK的GraphServiceClient,通过AccessTokenCredentialAdapter将已有的令牌适配为凭证,示例代码:

import com.microsoft.graph.models.User;
import com.microsoft.graph.models.Group;
import com.microsoft.graph.requests.GraphServiceClient;
import com.microsoft.graph.authentication.AccessTokenCredentialAdapter;
import okhttp3.OkHttpClient;

public class GraphClientExample {
    public static void useGraphClient(String accessToken) {
        // 用令牌创建凭证适配器
        AccessTokenCredentialAdapter credentialAdapter = new AccessTokenCredentialAdapter(accessToken);
        OkHttpClient httpClient = OkHttpClient.builder().build();
        
        // 初始化GraphServiceClient
        GraphServiceClient<okhttp3.Request> graphClient = GraphServiceClient
                .builder()
                .httpClient(httpClient)
                .authenticationProvider(credentialAdapter)
                .buildClient();

        // 调用用户列表API
        Iterable<User> users = graphClient.users().buildRequest().get();
        users.forEach(user -> System.out.println(user.displayName));

        // 调用组列表API
        Iterable<Group> groups = graphClient.groups().buildRequest().get();
        groups.forEach(group -> System.out.println(group.displayName));
    }
}

3. 令牌过期验证与重新生成

验证令牌是否过期

AccessToken对象提供了getExpiresAt()方法,可通过对比当前时间判断是否过期(建议提前5分钟校验,避免请求过程中令牌过期):

import java.time.Instant;

public boolean isTokenExpired(AccessToken token) {
    Instant expiryTime = token.getExpiresAt().minusSeconds(300);
    return Instant.now().isAfter(expiryTime);
}

优化令牌获取逻辑(自动缓存与刷新)

不要每次调用都新建ClientSecretCredential实例,该类内部已实现令牌缓存与自动刷新机制。建议复用同一个Credential实例,调用getTokenSync时指定所需的权限范围(之前代码传null不规范,应指定Graph API的权限范围):

import com.azure.identity.ClientSecretCredential;
import com.azure.identity.ClientSecretCredentialBuilder;
import com.azure.core.credential.AccessToken;
import com.azure.core.credential.TokenRequestContext;

// 全局复用该Credential实例
private static ClientSecretCredential credential;

static {
    credential = new ClientSecretCredentialBuilder()
            .clientId(clientId)
            .clientSecret(clientSecret)
            .tenantId(tenantId)
            .build();
}

public static AccessToken getValidAccessToken() {
    // 指定Graph API的默认权限范围
    TokenRequestContext context = new TokenRequestContext()
            .addScopes("https://graph.microsoft.com/.default");
    
    // 调用getTokenSync时,Credential会自动检查缓存,令牌过期则自动刷新
    return credential.getTokenSync(context);
}

每次需要令牌时,直接调用getValidAccessToken()即可,无需手动判断过期,Credential会自动处理缓存和刷新逻辑。


内容的提问来源于stack exchange,提问作者Avinash Reddy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 08:22:30