Definir permissões personalizadas em uma lista usando a interface REST

Sites do SharePoint, listas e itens de lista são tipos de SecurableObject. Por padrão, um objeto protegível herda as permissões de seu pai. Para definir permissões personalizadas de um objeto, você precisará interromper a herança para que ele pare de herdar permissões do site pai e depois definir novas permissões adicionando ou removendo atribuições de função.

Observação

Confira a seção Confira também para obter links para artigos sobre como definir permissões refinadas.

O exemplo de código neste artigo define permissões personalizadas em uma lista e, em seguida, altera as permissões do grupo para ele. O exemplo utiliza a interface REST para:

  • Obter a ID do grupo de destino. O exemplo usa a ID do grupo para obter as ligações de função atual para o grupo na lista e adicionar a nova função à lista.
  • Obter a ID da definição de função que define as novas permissões para o grupo. A ID é usada para adicionar a nova função à lista. Este exemplo usa uma definição de função existente para a nova função, mas você pode, opcionalmente, criar uma nova definição de função.
  • Interromper a herança de função na lista usando o método BreakRoleInheritance. O exemplo interrompe a herança de função, mas mantém o conjunto atual de funções. Como alternativa, você pode escolher não copiar as atribuições de função e adicionar o usuário atual ao nível de permissão Gerenciar.
  • Remova a atribuição de função atual do grupo na lista ao enviar uma solicitação DELETE para o ponto de extremidade de atribuição de função. (Se você optar por não copiar atribuições de função, ignore essa etapa.)
  • Adicionar uma atribuição de função para o grupo à lista usando o método AddRoleAssignment, que vincula o grupo à definição de função e adiciona a função à lista.

Pré-requisitos para usar o exemplo neste artigo

Para usar o exemplo neste artigo, você precisará de:

  • Um ambiente de desenvolvimento do SharePoint (isolamento de aplicativo necessário para cenários no local)
  • Visual Studio 2012 ou Visual Studio 2013 com Office Developer Tools para Visual Studio 2012 ou versão posterior

Você também precisará definir permissões de suplemento de Controle Total no escopo da Web. Somente usuários que têm permissões suficientes para alterar as permissões de lista (como os proprietários de sites) podem executar esse suplemento.

Exemplos: Definir permissões personalizadas em uma lista usando a interface REST

Os exemplos a seguir representam o conteúdo do arquivo App.js em um suplemento hospedado pelo SharePoint. O primeiro exemplo usa a biblioteca de domínio cruzado JavaScript para criar e enviar solicitações HTTP. O segundo exemplo usa solicitações jQuery AJAX.

Exemplo 1: solicitações de biblioteca entre domínios

'use strict';

// Change placeholder values before you run this code.
var listTitle = 'List 1';
var groupName = 'Group A';
var targetRoleDefinitionName = 'Contribute';
var appweburl;
var hostweburl;
var executor;
var groupId;
var targetRoleDefinitionId;

$(document).ready( function() {
  //Get the URI decoded URLs.
  hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
  appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));

  // Load the cross-domain library file and continue to the custom code.
  var scriptbase = hostweburl + "/_layouts/15/";
  $.getScript(scriptbase + "SP.RequestExecutor.js", getTargetGroupId);
});

// Get the ID of the target group.
function getTargetGroupId() {
  executor = new SP.RequestExecutor(appweburl);
  var endpointUri = appweburl + "/_api/SP.AppContextSite(@target)/web/sitegroups/getbyname('";
  endpointUri += groupName + "')/id" + "?@target='" + hostweburl + "'";

  executor.executeAsync({
    url: endpointUri,
    method: 'GET',
    headers: { 'accept':'application/json;odata=verbose' },
    success: function(responseData) {
      var jsonObject = JSON.parse(responseData.body);
      groupId = jsonObject.d.Id;
      getTargetRoleDefinitionId();
    },
    error: errorHandler
  });
}

// Get the ID of the role definition that defines the permissions
// you want to assign to the group.
function getTargetRoleDefinitionId() {
  var endpointUri = appweburl + "/_api/SP.AppContextSite(@target)/web/roledefinitions/getbyname('";
  endpointUri += targetRoleDefinitionName + "')/id" + "?@target='" + hostweburl + "'";

  executor.executeAsync({
    url: endpointUri,
    method: 'GET',
    headers: { 'accept':'application/json;odata=verbose' },
    success: function(responseData) {
      var jsonObject = JSON.parse(responseData.body)
      targetRoleDefinitionId = jsonObject.d.Id;
      breakRoleInheritanceOfList();
    },
    error: errorHandler
  });
}

// Break role inheritance on the list.
function breakRoleInheritanceOfList() {
  var endpointUri = appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('";
  endpointUri += listTitle + "')/breakroleinheritance(true)?@target='" + hostweburl + "'";

  executor.executeAsync({
    url: endpointUri,
    method: 'POST',
    headers: { 'X-RequestDigest':$('#__REQUESTDIGEST').val() },
    success: deleteCurrentRoleForGroup,
    error: errorHandler
  });
}

// Remove the current role assignment for the group on the list.
function deleteCurrentRoleForGroup() {
  var endpointUri = appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('";
  endpointUri += listTitle + "')/roleassignments/getbyprincipalid('" + groupId + "')?@target='" + hostweburl + "'";

  executor.executeAsync({
    url: endpointUri,
    method: 'POST',
    headers: {
      'X-RequestDigest':$('#__REQUESTDIGEST').val(),
      'X-HTTP-Method':'DELETE'
    },
    success: setNewPermissionsForGroup,
    error: errorHandler
  });
}

// Add the new role assignment for the group on the list.
function setNewPermissionsForGroup() {
  var endpointUri = appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('";
  endpointUri += listTitle + "')/roleassignments/addroleassignment(principalid=" + groupId;
  endpointUri += ",roledefid=" + targetRoleDefinitionId + ")?@target='" + hostweburl + "'";

  executor.executeAsync({
    url: endpointUri,
    method: 'POST',
    headers: { 'X-RequestDigest':$('#__REQUESTDIGEST').val() },
    success: successHandler,
    error: errorHandler
  });
}

// Get parameters from the query string.
// For production purposes you may want to use a library to handle the query string.
function getQueryStringParameter(paramToRetrieve) {
  var params = document.URL.split("?")[1].split("&");
  for (var i = 0; i < params.length; i = i + 1) {
    var singleParam = params[i].split("=");
    if (singleParam[0] == paramToRetrieve) return singleParam[1];
  }
}

function successHandler() {
  alert('Request succeeded.');
}

function errorHandler(xhr, ajaxOptions, thrownError) {
  alert('Request failed: ' + xhr.status + '\n' + thrownError + '\n' + xhr.responseText);
}

Exemplo 2: solicitações jQuery AJAX

// Change placeholder values before you run this code.
var siteUrl = 'http://server/site';
var listTitle = 'List 1';
var groupName = 'Group A';
var targetRoleDefinitionName = 'Contribute';
var groupId;
var targetRoleDefinitionId;

$(document).ready( function() {
  getTargetGroupId();
});

// Get the ID of the target group.
function getTargetGroupId() {
  $.ajax({
    url: siteUrl + '/_api/web/sitegroups/getbyname(\'' + groupName + '\')/id',
    type: 'GET',
    headers: { 'accept':'application/json;odata=verbose' },
    success: function(responseData) {
      groupId = responseData.d.Id;
      getTargetRoleDefinitionId();
    },
    error: errorHandler
  });
}

// Get the ID of the role definition that defines the permissions
// you want to assign to the group.
function getTargetRoleDefinitionId() {
  $.ajax({
    url: siteUrl + '/_api/web/roledefinitions/getbyname(\''
        + targetRoleDefinitionName + '\')/id',
    type: 'GET',
    headers: { 'accept':'application/json;odata=verbose' },
    success: function(responseData) {
      targetRoleDefinitionId = responseData.d.Id;
      breakRoleInheritanceOfList();
    },
    error: errorHandler
  });
}

// Break role inheritance on the list.
function breakRoleInheritanceOfList() {
  $.ajax({
    url: siteUrl + '/_api/web/lists/getbytitle(\'' + listTitle
        + '\')/breakroleinheritance(true)',
    type: 'POST',
    headers: { 'X-RequestDigest':$('#__REQUESTDIGEST').val() },
    success: deleteCurrentRoleForGroup,
    error: errorHandler
  });
}

// Remove the current role assignment for the group on the list.
function deleteCurrentRoleForGroup() {
  $.ajax({
    url: siteUrl + '/_api/web/lists/getbytitle(\'' + listTitle
        + '\')/roleassignments/getbyprincipalid(' + groupId + ')',
    type: 'POST',
    headers: {
      'X-RequestDigest':$('#__REQUESTDIGEST').val(),
      'X-HTTP-Method':'DELETE'
    },
    success: setNewPermissionsForGroup,
    error: errorHandler
  });
}

// Add the new role assignment for the group on the list.
function setNewPermissionsForGroup() {
  $.ajax({
    url: siteUrl + '/_api/web/lists/getbytitle(\'' + listTitle
        + '\')/roleassignments/addroleassignment(principalid='
        + groupId + ',roledefid=' + targetRoleDefinitionId + ')',
    type: 'POST',
    headers: { 'X-RequestDigest':$('#__REQUESTDIGEST').val() },
    success: successHandler,
    error: errorHandler
  });
}

function successHandler() {
  alert('Request succeeded.');
}

function errorHandler(xhr, ajaxOptions, thrownError) {
  alert('Request failed: ' + xhr.status + '\n' + thrownError + '\n' + xhr.responseText);
}

Confira também