使用 REST 接口设置列表上的自定义权限Set custom permissions on a list by using the REST interface

SharePoint 网站、列表和列表项均属于 SecurableObject 类型。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.

备注

请参阅另请参阅部分,获取介绍如何设置细化权限的文章链接。See the See also section for links to articles about setting fine-grained permissions.

本文中的代码示例设置列表的自定义权限,然后更改某个组对该列表的权限。本示例使用 REST 接口执行以下操作: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:

  • 获取目标组的 ID。本示例使用 ID 获取列表中组的当前角色绑定,并将新角色添加到列表中。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.
  • 获取定义组的新权限的角色定义的 ID。ID 用于将新角色添加到列表中。本示例使用新角色的现有角色定义,但您可以选择创建新的角色定义。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.
  • 通过使用 BreakRoleInheritance 方法中断列表上的角色继承。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.
  • 通过向角色分配终结点发送 DELETE 请求,移除列表上组的当前角色分配。(如果您选择不复制任何角色分配,您可跳过此步骤。)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.)
  • 使用 AddRoleAssignment 方法向列表添加组的角色分配,这可将组绑定到角色定义并向列表添加该角色。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.

使用本文中示例的先决条件Prerequisites for using the example in this article

若要使用本文中的示例,需要具备:To use the example in this article, you'll need:

  • 一个 SharePoint 开发环境(本地方案需要应用隔离)A SharePoint development environment (app isolation required for on-premises scenarios)
  • Visual Studio 2012 或 Visual Studio 2013(带 Visual Studio 2012 的 Office 开发人员工具)或更高版本Visual Studio 2012 or Visual Studio 2013 with Office Developer Tools for Visual Studio 2012, or later

您还需要在 Web 作用域中设置 Full Control外接程序权限。只有具有更改列表权限的充分权限的用户(如网站所有者)才能运行此外接程序。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.

示例:使用 REST 接口设置列表上的自定义权限Examples: Set custom permissions on a list by using the REST interface

以下示例表示 SharePoint 托管的外接程序中的 App.js 文件的内容。第一个示例使用 JavaScript 跨域库生成并发送 HTTP 请求。第二个示例使用 jQuery AJAX 请求。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.

示例 1:跨域库请求Example 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);
}

示例 2:jQuery AJAX 请求Example 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);
}

另请参阅See also