401 尝试使用获取的访问令牌调用 Office 365 API 时未授权



我正在使用Java创建一个简单的守护程序或服务应用程序(不是Web应用程序(来调用Office 365日历API。我遵循了本指南在服务或守护程序中调用 Microsoft Graph,但当我尝试使用访问令牌调用 API 时,我收到 401 错误。我已使用所有 Graph 授权将应用注册到 Azure 门户,并已按照本指南的步骤 1:获取证书或创建自签名证书制作证书。这是我的访问令牌请求代码:'

    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,因此我认为我的令牌请求中有问题。有人可以帮助我吗?

从您的代码中,您正在获取资源 :https://graph.microsoft.com 的令牌,但是在使用该令牌的 api 调用中,您正在调用 Outlook 邮件 REST API(https://outlook.office.com/(。如果要调用 Microsoft Graph API(https://graph.microsoft.com(,则应查看 Microsoft Graph API 获取日历。

第二个问题是你使用的是客户端凭证流(app的标识(,你不能使用用户身份(/me(,因为访问令牌中没有包含用户信息。使用微软图形API,您可以使用GET /users/{id | userPrincipalName}/calendars

最新更新