分享四步用java创建microsoft graph client,具体如下:
一、需要的类
1.1jackson-core-2.14.1jar
1.2jackson-databind-2.14.1.jar
1.3microsoft-graph-5.49.0.jar
1.4microsoft-graph-core-2.0.16.jar
1.5okhttp-4.10.0.jar
1.6gson-2.10.1.jar
1.7guava-jdk5-13.0.jar
1.8kotlin-stdlib-1.8.10.jar
1.9okio-2.1.0.jar
二、申请Micosoft Application授权
此步骤获取到如下参数
2.1 tenantId //租户ID
2.2 clientId //客户端Id
2.3 clientSecret //客户端密码
三、获取访问Token
private staticString getAccessToken(){
String sReturn = "";
String tenantId ="XXX";
String clientId = "XXX";
String clientSecret = "xxx";
String authUrl = "https://login.microsoftonline.com/"+ tenantId + "/oauth2/token";
try{
URL url = new URL(authUrl);
HttpURLConnection conn =(HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
conn.setDoOutput(true);
OutputStreamWriter out = newOutputStreamWriter(conn.getOutputStream());
String postData ="grant_type=client_credentials"
+ "&client_id=" +clientId
+"&client_secret=" + clientSecret
+"&resource=https://graph.microsoft.com";
out.write(postData);
out.close();
BufferedReader in = newBufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = newStringBuffer();
while ((inputLine = in.readLine())!= null) {
response.append(inputLine);
}
in.close();
String json = response.toString();
Map<String, Object> map = newHashMap<>();
map = newObjectMapper().readValue(json, new TypeReference<Map<String,Object>>() {});
sReturn = (String)map.get("access_token");
}catch(Exception e){
System.out.println("getAccessToken get error is : " + e);
}
return sReturn;
}
四、创建Microsoft graph client
private staticGraphServiceClient getGraphClient() {
GraphServiceClient graphClient = null;
try{
IAuthenticationProviderauthProvider = new IAuthenticationProvider() {
@Override
publicCompletableFuture<String> getAuthorizationTokenAsync(URL requestUrl) {
CompletableFuture<String> future = newCompletableFuture<>();
try{
future.complete(getAccessToken());
}catch(Exception e){
System.out.println("getAuthorizationTokenAsync get error is :" + e);
}
return future;
}
};
graphClient =GraphServiceClient.builder().authenticationProvider(authProvider).buildClient();
}catch(Exception e){
System.out.println("get erroris : " + e);
}
return graphClient;
}