Azure Graph Rest API Java客户端凭据流Scope配置错误问题
解决Microsoft Graph Beta SDK Java客户端凭据流Scope错误问题
你在使用Microsoft Graph Beta SDK Java尝试列出AAD租户所有用户时,遇到了AADSTS1002012错误,核心原因是客户端凭据流的Scope格式不正确。
你的原代码中Scope设置为:
List<String> scopes= Arrays.asList("https://graph.microsoft.com/User.Read.All");
报错信息:
Caused by: java.io.IOException:
java.util.concurrent.ExecutionException:
com.microsoft.aad.msal4j.MsalServiceException:
AADSTS1002012: The provided value for scope https://graph.microsoft.com/User.Read.All openid profile offline_access is not valid. Client credential flows must have a scope value with /.default suffixed to the resource identifier (application ID URI).
正确的Scope设置
客户端凭据流属于应用权限模式,不能像委托权限那样指定具体的权限名称,必须使用{资源URI}/.default的格式,这个格式会自动包含所有已为你的Azure AD应用配置的应用权限。
修改Scope代码为:
List<String> scopes = Arrays.asList("https://graph.microsoft.com/.default");
关键注意事项
- 确保你的Azure AD应用已在Azure门户中添加User.Read.All的应用权限(不是委托权限),并且完成了管理员同意,否则会出现权限不足的错误。
- 原代码中的
AzureProfile包含了subscriptionId,这个是Azure资源订阅ID,和Microsoft Graph操作无关,可以简化移除,避免不必要的参数依赖。
修改后的完整代码示例
import com.azure.identity.ClientSecretCredential; import com.azure.identity.ClientSecretCredentialBuilder; import com.microsoft.graph.authentication.TokenCredentialAuthProvider; import com.microsoft.graph.beta.models.User; import com.microsoft.graph.beta.models.UserCollectionPage; import com.microsoft.graph.beta.requests.GraphServiceClient; import com.microsoft.graph.http.Request; import java.util.Arrays; import java.util.List; public class ListUsers { public static void main(String[] args) { String tenantId = "你的租户ID"; String clientId = "你的客户端ID"; String clientSecret = "你的客户端密钥"; // 正确的Scope设置 List<String> scopes = Arrays.asList("https://graph.microsoft.com/.default"); // 构建ClientSecretCredential final ClientSecretCredential credential = new ClientSecretCredentialBuilder() .clientId(clientId) .clientSecret(clientSecret) .tenantId(tenantId) .authorityHost("https://login.microsoftonline.com/") .build(); TokenCredentialAuthProvider tokenCredentialAuthProvider = new TokenCredentialAuthProvider(scopes, credential); // 构建GraphServiceClient GraphServiceClient<Request> graphClient = GraphServiceClient .builder() .authenticationProvider(tokenCredentialAuthProvider) .buildClient(); // 获取用户列表 UserCollectionPage users = graphClient.users() .buildRequest() .get(); // 遍历输出用户信息 for(User user: users.getCurrentPage()){ System.out.println(user.displayName); System.out.println(user.id); System.out.println(user.userPrincipalName); } } }
内容的提问来源于stack exchange,提问作者Ihsan Haikal
相关产品推荐
相关产品推荐

