2016-11-23 1 views
0

Я пытаюсь добавить роль пользователя, как показано нижеНедостаточная ошибка привилегий при попытке добавить роль с помощью графика API

/** 
passing values to addUserToGroup method 
**/                     
addUserToGroup("e5911e4e-3d44-448c-bb42-dd6d51855cd4", "d405c6df-0af8-4e3b-95e4-4d06e542189e", "role"); 

private static String addUserToGroup(
     String userId, 
     String groupId, 
     String objectName) throws OfficeException { 

    String newKey = null;    

     /** 
     * Setup the JSON Body 
     */   
     JSONObject jsonObj=new JSONObject(); 

     String objectLink = String.format("https://%s/%s/directoryObjects/%s", 
        AppParameter.getProtectedResourceHostName(), 
        AppParameter.getTenantContextId(), 
        userId); 

     try{ 
     jsonObj.put("url", objectLink); 

     /** 
     * Convert the JSON object into a string. 
     */ 
     String data = jsonObj.toString(); 


     if(objectName.equals("roledelete")) 
     { 

     } 
     else if(objectName.equals("role")) 
     { 
      newKey = handlRequestPostJSON(
        String.format("/%ss/%s/$links/members", objectName, groupId), 
        null, 
        data, 
        "addUserToGroup"); 

     } 

      return newKey; 

    }catch(Exception e){ 
     throw new OfficeException(AppParameter.ErrorCreatingJSON,e.getMessage(), e, null); 
     } 
} 

/** метод handlRequestPostJSON **/

public static String handlRequestPostJSON(String path, String queryOption, String data, String opName){ 

     URL url = null; 
     HttpURLConnection conn = null; 
     String queryOptionAdd = ""; 
     String apiVersion = AppParameter.getDataContractVersion(); 

     try { 
      /** 
      * Form the request uri by specifying the individual components of the 
      * URI. 
      */ 
      if (queryOption == null) 
      { 
       queryOptionAdd = apiVersion;     
      } 
      else 
      { 
       queryOptionAdd = queryOption + "&" + apiVersion;     
      } 

      URI uri = new URI(
        AppParameter.PROTOCOL_NAME, 
        AppParameter.getRestServiceHost(), 
        "/" + AppParameter.getTenantContextId() + path, 
        queryOptionAdd, 
        null); 



      /** 
      * Open an URL Connection. 
      */ 
      url = uri.toURL(); 
      conn = (HttpURLConnection) url.openConnection(); 

      /** 
      * Set method to POST. 
      */ 
      conn.setRequestMethod("POST"); 

      if(opName.equalsIgnoreCase("roledelete")) 
      { 
       conn.setRequestMethod("DELETE"); 
      } 

      /** 
      * Set the appropriate request header fields. 
      */ 
      conn.setRequestProperty(AppParameter.AUTHORIZATION_HEADER, AppParameter.getAccessToken()); 
      conn.setRequestProperty("Accept", "application/json"); 

      /** 
      * If the request for create an user or update an user, the appropriate content type would 
      * be application/json. 
      */ 
      if(opName.equalsIgnoreCase("createUser") || opName.equalsIgnoreCase("updateUser") ){ 
      conn.setRequestProperty("Content-Type", "application/json"); 
      } 

      /** 
      * If the operation is to add an user to a group/role, 
      * the content type should be set to "application/json". 
      */ 
      else if(opName.equalsIgnoreCase("addUserToGroup")){ 
       conn.setRequestProperty("Content-Type", "application/json"); 
      } 


      /** 
      * If the operation is for update user, then we need to send a 
      * PATCH request, not a POST request. Therefore, we use the X-HTTP-METHOD 
      * header field to specify that this request is intended to be used as a 
      * PATCH request. 
      */ 
      if(opName.equalsIgnoreCase("updateUser")){ 
       conn.setRequestProperty("X-HTTP-Method", "PATCH");   
      } 



      /** 
      * Send the http message payload to the server. 
      */ 
      conn.setDoOutput(true);   
      OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
      wr.write(data); 
      wr.flush(); 


      /** 
      * Get the message response from the server. 
      */ 
      BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));   
      String line, response = "";   
      while((line=rd.readLine()) != null){ 
       response += line; 
      } 

      /** 
      * Close the streams. 
      */ 
      wr.close(); 
      rd.close(); 

      int responseCode = conn.getResponseCode(); 
      System.out.println("Response Code: " + responseCode);  


      return (Integer.toString(responseCode)); 


     } catch (Exception e2) { 

      try { 
       int responseCode = conn.getResponseCode(); 
       System.out.println("Response Code: " + responseCode); 
      } catch (IOException e1) { 
       // TODO Auto-generated catch block 
       e1.printStackTrace(); 
      } 

      /** 
      * Get the error stream. 
      */ 
      BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getErrorStream())); 
      StringBuffer stringBuf = new StringBuffer(); 
      String inputLine; 
      try { 
       while ((inputLine = reader.readLine()) != null) { 
        stringBuf.append(inputLine); 
       } 
      } catch (IOException e) { 
       // TODO HANDLE THE EXCEPTION 

      } 
      String response = stringBuf.toString(); 
      System.out.println(response); 
      return response; 

     } 

    } 

Он показывает ошибку следующим образом

{"odata.error": {"code": "Authorization_RequestDenied", "message": {"lang": "en", "value": "Недостаточно привилегий для завершения операции. "}," reques tId ":" 05318157-1c3b-4410-9be5-ce6c6246514c "," date ":" 2016-11-23T04: 27: 53 "}}

Пожалуйста, помогите мне. Заранее спасибо.

ответ

0

Ваше приложение должно быть настроено с необходимыми разрешениями в AAD.

Наверное, лучше всего позволить ему получить доступ к AAD с теми же правами, что и подписанный пользователь, а затем войти в приложение в качестве администратора Azure AD.

Проверьте вкладку «Права доступа к другим приложениям» в конфигурации приложения на классическом портале Azure (https://manage.windowsazure.com).

0

Для вызова графика ADRE ADRE успешно используется делегат-токен, необходимо выполнить два условия. Во-первых, токен содержит достаточное разрешение для работы с ресурсом. Во-вторых, пользователи входа имеют достаточное разрешение на управление ресурсом.

Например, чтобы добавить членов группы в группу, токен должен содержать разрешение Directory.ReadWrite.All, Directory.AccessAsUser.All. И у пользователя-знака также должно быть разрешение на управление такими группами, как Global admin.

Подробнее о разрешениях и областях, вы можете обратиться here.

Смежные вопросы