Microsoft IdentityModel Tokens AudienceUriValidationFailedException при попытке доступа к Sharepoint с помощью REST API - PullRequest
0 голосов
/ 10 июля 2020

Я изо всех сил пытаюсь понять совершенно новую идею доступа к контенту Sharepoint моей организации с помощью Sahrepoint REST API, и я пытаюсь реализовать его в java. Моя цель - прочитать все файлы в папке «ab c», которая находится в папке «Документы». Шаги, которые я сделал.

  1. Зарегистрируйте приложение: нажмите «Создать идентификатор клиента», нажмите «Создать секрет клиента», «Предоставить заголовок», «Предоставить домен приложения как имя компании.onmicrosoft» и «Отправить URI запроса как * 1006. *https://companyname.sharepoint.com/Shared%20Documents/Forms/AllItems.aspx

    Зарегистрировано приложение. У меня есть идентификатор клиента, секрет клиента и идентификатор клиента. Я использовал приведенный ниже код для создания токена доступа

public String getSpToken(String shp_clientId, String shp_tenantId, String shp_clientSecret) {
        
        String accessToken = "";
        try {

            // AccessToken url
            String wsURL = "https://accounts.accesscontrol.windows.net/" + shp_tenantId + "/tokens/OAuth/2";

            URL url = new URL(wsURL);
            URLConnection connection = url.openConnection();
            HttpURLConnection httpConn = (HttpURLConnection) connection;

            // Set header
            httpConn.setRequestProperty("Content-Type", "  ");
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);
            httpConn.setRequestMethod("POST");

            // Prepare RequestData
            String jsonParam = "grant_type=client_credentials" 
                    + "&client_id=" + shp_clientId + "@" + shp_tenantId 
                    + "&client_secret=" + shp_clientSecret
                    + "&resource=00000003-0000-0ff1-ce00-000000000000/www.companyname.sharepoint.com@" + shp_tenantId;
            

            // Send Request
            DataOutputStream wr = new DataOutputStream(httpConn.getOutputStream());
            wr.writeBytes(jsonParam);
            wr.flush();
            wr.close();

            // Read the response.
            InputStreamReader isr = null;
            if (httpConn.getResponseCode() == 200) {
                isr = new InputStreamReader(httpConn.getInputStream());
            } else {
                isr = new InputStreamReader(httpConn.getErrorStream());
            }

            BufferedReader in = new BufferedReader(isr);
            String responseString = "";
            String outputString = "";

            // Write response to a String.
            while ((responseString = in.readLine()) != null) {
                outputString = outputString + responseString;
            }

            //Printing the response to the console
            System.out.println("Output from the REST" + outputString);
            
            // Extracting accessToken from string, here response (outputString)is a Json format string
            if (outputString.indexOf("access_token\":\"") > -1) {
                int i1 = outputString.indexOf("access_token\":\"");
                String str1 = outputString.substring(i1 + 15);
                int i2 = str1.indexOf("\"}");
                String str2 = str1.substring(0, i2);
                accessToken = str2;
            }
            
            //Printing the access token
            System.out.println("Access token is " + accessToken);
            
        } catch (Exception e) {
            accessToken = "Error: " + e.getMessage();           
        }
        return accessToken;
    }

Теперь, когда у меня есть токен доступа в строковой переменной accessToken, я использовал следующий код для чтения имен файлов внутри папка «ab c» в папке «Документы» с использованием метода readFiles ()

public void readFiles(String accessToken) {
        
        try {       
               //Frame SharePoint siteURL           
               String siteURL = "https://companyname.sharepoint.com";
                    
               //Frame SharePoint URL to retrieve the name of all of the files in a folder
               String wsUrl = siteURL + "/_api/web/GetFolderByServerRelativeUrl('Shared%20Documents/abc')/Files";
                
               //Create HttpURLConnection
               URL url = new URL(wsUrl);
               URLConnection connection = url.openConnection();
               HttpURLConnection httpConn = (HttpURLConnection) connection;
                                    
               //Set Header     
               httpConn.setRequestMethod("GET");                
               httpConn.setRequestProperty("Authorization", "Bearer " + accessToken);
               httpConn.setRequestProperty("accept", "application/json;odata=verbose"); //To get response in JSON
               //httpConn.setRequestProperty("AllowAppOnlyPolicy", "true");
               //httpConn.setRequestProperty("Scope", "http://sharepoint/content/sitecollection/web\" Right=\"FullControl");
               
               //Read the response
               String httpResponseStr = "";
               InputStreamReader isr = null;
               System.out.println(httpConn.getResponseCode());
               if (httpConn.getResponseCode() == 200) {
                 isr = new InputStreamReader(httpConn.getInputStream());
               } else {
                 isr = new InputStreamReader(httpConn.getErrorStream());
               }        
               BufferedReader in = new BufferedReader(isr);             
               String strLine = "";
               while ((strLine = in.readLine()) != null) {
                 httpResponseStr = httpResponseStr + strLine;
               }
               
               //Print response
               System.out.println(httpResponseStr); 
               
            } catch (Exception e) {
               System.out.println("Error while reading file: " + e.getMessage());
            }       
    }

}

Когда я выполняю приведенный выше код, я получаю {«error_description»: «Исключение типа 'Microsoft.IdentityModel.Tokens. AudienceUriValidationFailedException 'было брошено. "}. Может ли кто-нибудь помочь мне понять, что я делаю не так? Я сижу на этом несколько дней и не могу решить. Пожалуйста, помогите!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...