我使用Java创建一个简单的守护程序或服务应用程序(而不是Web应用程序)来调用Office 365 Calendar API。我已按照本指南Call Microsoft Graph in a service or daemon app进行操作,但当我尝试使用访问令牌调用API时,我收到401错误。 我已经使用所有图表授权将应用程序注册到azure门户网站,并且我已按照本指南的第1步Get a certificate or create a self-signed certificate制作了证书。这是访问令牌请求的代码:`
String accessToken="";
String token_endpoint = "https://login.windows.net/<mytenant>/oauth2/token";
String grant_type = "client_credentials";
String client_secret = <mysecret>;
String resource = "https://graph.microsoft.com";
String client_id = <myclient>;
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(token_endpoint);
List<NameValuePair> parameters = new ArrayList<>();
parameters.add(new BasicNameValuePair("grant_type", grant_type));
parameters.add(new BasicNameValuePair("client_id", client_id));
parameters.add(new BasicNameValuePair("client_secret", client_secret));
parameters.add(new BasicNameValuePair("resource", resource));
httpPost.setEntity(new UrlEncodedFormEntity(parameters));
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity();
//parsing
JSONParser parser = new JSONParser();
Scanner httpResponseScanner = new Scanner(entity.getContent());
String jsonString = httpResponseScanner.nextLine();
//System.out.println(jsonString);
JSONObject json = (JSONObject) parser.parse(jsonString);
accessToken = json.get("access_token").toString();
EntityUtils.consume(entity);
}
return accessToken;`
这是我的API调用代码:`
String apiURL = "https://outlook.office.com/api/v2.0/me/calendars";
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(apiURL);
httpGet.addHeader("Accept", "application/json");
httpGet.addHeader("Authorization", "Bearer " + accessToken);
try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
}`
我已经使用无效的签名响应测试了我的访问令牌到jwt.io,所以我认为我的令牌请求有问题。有人可以帮帮我吗?
答案 0 :(得分:0)
从您的代码中,您正在获取资源令牌:https://graph.microsoft.com,但在使用该令牌的api调用中,您正在调用outlook mail rest api(https://outlook.office.com/)。如果要调用microsoft graph api(https://graph.microsoft.com),则应检查microsoft graph api get calendars。
第二个问题是您正在使用客户端凭据流(应用程序的身份),您无法使用用户身份(/me
),因为访问令牌中没有包含用户信息。使用microsoft graph api,您可以使用GET /users/{id | userPrincipalName}/calendars