Establecer permisos personalizados en una lista usando la interfaz RESTSet custom permissions on a list by using the REST interface

Los sitios, las listas y los elementos de lista de SharePoint son tipos de SecurableObject. De manera predeterminada, un objeto protegible hereda los permisos de su elemento primario. Para establecer permisos personalizados en un objeto, tiene que romper su herencia para que deje de heredar permisos del elemento primario y, luego, definir permisos nuevos agregando o eliminando asignaciones de roles.SharePoint sites, lists, and list items are types of SecurableObject. By default, a securable object inherits the permissions of its parent. To set custom permissions for an object, you need to break its inheritance so that it stops inheriting permissions from its parent, and then define new permissions by adding or removing role assignments.

Nota

Vea la sección Ver también para obtener vínculos a artículos sobre la configuración de la personalización avanzada de permisos.See the See also section for links to articles about setting fine-grained permissions.

El ejemplo de código de este artículo establece permisos personalizados en una lista y luego cambia los permisos que un grupo tiene en ella. En el ejemplo se usa la interfaz REST para:The code example in this article sets custom permissions on a list, and then changes a group's permissions to it. The example uses the REST interface to:

  • Obtener el id. del grupo de destino. En el ejemplo se usa el id. de grupo para obtener los enlaces de rol actuales para el grupo que hay en la lista y agregar el nuevo rol a la lista.Get the ID of the target group. The example uses the group ID to get the current role bindings for the group on the list and to add the new role to the list.

  • Obtener el id. de la definición de rol que define los nuevos permisos para el grupo. El id. se usa para agregar el nuevo rol a la lista. En este ejemplo se usa una definición de rol existente para el nuevo rol, pero también puede crear una nueva definición de rol.Get the ID of the role definition that defines the new permissions for the group. The ID is used to add the new role to the list. This example uses an existing role definition for the new role, but you can optionally create a new role definition.

  • Interrumpir la herencia de roles en la lista usando el método BreakRoleInheritance. En el ejemplo, se rompe la herencia de rol, pero se mantiene el conjunto actual de roles. (Como alternativa, puede elegir no copiar las asignaciones de roles y agregar el usuario actual al nivel de permisos Administrar).Break role inheritance on the list by using the BreakRoleInheritance method. The example breaks role inheritance but keeps the current set of roles. (Alternatively, you can choose not to copy any role assignments and to add the current user to the Manage permission level.)

  • Quitar la asignación de rol actual del grupo que hay en la lista enviando una solicitud de eliminación (DELETE) al extremo de la asignación de rol. (Si no decide copiar las asignaciones de rol, omita este paso).Remove the group's current role assignment on the list by sending a DELETE request to the role assignment endpoint. (If you choose not to copy any role assignments, you would skip this step.)

  • Agregar una asignación de rol para el grupo en la lista usando el método AddRoleAssignment, que enlaza el grupo a la definición de rol y agrega el rol a la lista.Add a role assignment for the group to the list by using the AddRoleAssignment method, which binds the group to the role definition and adds the role to the list.

Requisitos previos para usar los ejemplos de este artículoPrerequisites for using the example in this article

Para usar el ejemplo de este artículo, necesitará:To use the example in this article, you'll need:

  • Un entorno de desarrollo de SharePoint (hay que aislar la aplicación en los escenarios locales)A SharePoint development environment (app isolation required for on-premises scenarios)

  • Visual Studio 2012 o Visual Studio 2013 con Office Developer Tools para Visual Studio 2012, o versiones posterioresVisual Studio 2012 or Visual Studio 2013 with Office Developer Tools for Visual Studio 2012, or later

También tendrá que establecer los permisos del complemento Full Control en el ámbito Web. Solo los usuarios que tengan permisos suficientes para cambiar los permisos de la lista (como los propietarios de sitios) pueden ejecutar este complemento.You'll also need to set Full Control add-in permissions at the Web scope. Only users who have sufficient permissions to change list permissions (such as site owners) can run this add-in.

Ejemplos: Establecer permisos personalizados en una lista usando la interfaz RESTExamples: Set custom permissions on a list by using the REST interface

En los ejemplos siguientes se representa el contenido del archivo App.js de un complemento hospedado en SharePoint. En el primer ejemplo, se usa la biblioteca entre dominios de JavaScript para compilar y enviar solicitudes HTTP. En el segundo ejemplo, se usan las solicitudes AJAX de jQuery.The following examples represent the contents of the App.js file in a SharePoint-hosted add-in. The first example uses the JavaScript cross-domain library to build and send HTTP requests. The second example uses jQuery AJAX requests.

Before you run the code, replace the placeholder values with actual values. If you're using a different language or environment, you need to add or change some request components. For more information, see How REST requests differ by environment.Before you run the code, replace the placeholder values with actual values. If you're using a different language or environment, you need to add or change some request components. For more information, see How REST requests differ by environment.

Ejemplo 1: solicitudes de bibliotecas entre dominiosExample 1: Cross-domain library requests

'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);
}

Ejemplo 2: solicitudes AJAX de jQueryExample 2: jQuery AJAX requests

// 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);
}

Vea tambiénSee also