Назначение административных ролей с помощью PIM для API Microsoft Entra ролей
Статья
управление привилегированными пользователями (PIM) позволяет организациям управлять административным доступом к ресурсам в Microsoft Entra ID. Административный доступ может осуществляться через группы с возможностью назначения ролей или Microsoft Entra роли. PIM помогает управлять рисками привилегированного доступа, ограничивая, когда доступ активен, управляя область доступа и предоставляя проверяемый журнал привилегированного доступа.
Компания Contoso хочет назначить административные роли субъектам с помощью групп безопасности. Компания назначает право на участие вместо постоянно активных административных ролей. Этот метод эффективен следующими способами:
Удаление существующих или добавление дополнительных участников группы также удалит администраторов.
Члены группы наследуют соответствующее назначение ролей. Вы можете назначить группе больше ролей, а не назначать роли непосредственно отдельным пользователям.
Назначение прав доступа вместо постоянно активной привилегии администратора пользователей позволяет компании обеспечить JIT-доступ, который предоставляет временные разрешения на выполнение привилегированных задач. Когда участнику группы необходимо использовать привилегии, он активирует свое назначение на временное время. Все записи активаций ролей проверяются компанией.
В этом руководстве рассказывается, как:
Create группу безопасности с возможностью назначения ролей.
Сделайте группу безопасности, назначаемую роли, правой на административную роль.
Предоставление JIT-доступа пользователю путем активации соответствующего назначения.
Предварительные условия
Для работы с этим руководством вам потребуются следующие ресурсы и привилегии:
Рабочий клиент Microsoft Entra с включенной лицензией Microsoft Entra ID P2 или Управление Microsoft Entra ID.
Войдите в клиент API, например Graph Обозреватель, чтобы вызвать Microsoft Graph с учетной записью, которая имеет по крайней мере роль администратора привилегированных ролей.
[Необязательно] Запустите новый анонимный сеанс в другом браузере. Вы выполните вход далее в этом руководстве.
Тестовый пользователь, для которых включена MFA, и у вас есть доступ к учетной записи приложения Microsoft Authenticator.
Предоставьте себе следующие делегированные разрешения: Group.ReadWrite.All, Directory.Read.All, RoleEligibilitySchedule.ReadWrite.Directoryи RoleAssignmentSchedule.ReadWrite.Directoryи RoleManagement.ReadWrite.Directory.
Шаг 1. Create группу безопасности с возможностью назначения ролей
Назначьте себя владельцем группы, а участниками — вас и тестового пользователя.
Запрос: Create группу с возможностью назначения ролей
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.Models;
var requestBody = new Group
{
Description = "IT Helpdesk to support Contoso employees",
DisplayName = "IT Helpdesk (User)",
MailEnabled = false,
MailNickname = "userHelpdesk",
SecurityEnabled = true,
IsAssignableToRole = true,
AdditionalData = new Dictionary<string, object>
{
{
"owners@odata.bind" , new List<string>
{
"https://graph.microsoft.com/v1.0/users/1ed8ac56-4827-4733-8f80-86adc2e67db5",
}
},
{
"members@odata.bind" , new List<string>
{
"https://graph.microsoft.com/v1.0/users/1ed8ac56-4827-4733-8f80-86adc2e67db5",
"https://graph.microsoft.com/v1.0/users/7146daa8-1b4b-4a66-b2f7-cf593d03c8d2",
}
},
},
};
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Groups.PostAsync(requestBody);
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
Group group = new Group();
group.setDescription("IT Helpdesk to support Contoso employees");
group.setDisplayName("IT Helpdesk (User)");
group.setMailEnabled(false);
group.setMailNickname("userHelpdesk");
group.setSecurityEnabled(true);
group.setIsAssignableToRole(true);
HashMap<String, Object> additionalData = new HashMap<String, Object>();
LinkedList<String> ownersOdataBind = new LinkedList<String>();
ownersOdataBind.add("https://graph.microsoft.com/v1.0/users/1ed8ac56-4827-4733-8f80-86adc2e67db5");
additionalData.put("owners@odata.bind", ownersOdataBind);
LinkedList<String> membersOdataBind = new LinkedList<String>();
membersOdataBind.add("https://graph.microsoft.com/v1.0/users/1ed8ac56-4827-4733-8f80-86adc2e67db5");
membersOdataBind.add("https://graph.microsoft.com/v1.0/users/7146daa8-1b4b-4a66-b2f7-cf593d03c8d2");
additionalData.put("members@odata.bind", membersOdataBind);
group.setAdditionalData(additionalData);
Group result = graphClient.groups().post(group);
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.models.group import Group
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
request_body = Group(
description = "IT Helpdesk to support Contoso employees",
display_name = "IT Helpdesk (User)",
mail_enabled = False,
mail_nickname = "userHelpdesk",
security_enabled = True,
is_assignable_to_role = True,
additional_data = {
"owners@odata_bind" : [
"https://graph.microsoft.com/v1.0/users/1ed8ac56-4827-4733-8f80-86adc2e67db5",
],
"members@odata_bind" : [
"https://graph.microsoft.com/v1.0/users/1ed8ac56-4827-4733-8f80-86adc2e67db5",
"https://graph.microsoft.com/v1.0/users/7146daa8-1b4b-4a66-b2f7-cf593d03c8d2",
],
}
)
result = await graph_client.groups.post(request_body)
Теперь, когда у вас есть группа безопасности с возможностью назначения ролей, назначьте ей право на роль администратора пользователей в течение одного года. Оставьте допустимое назначение всем клиентом. Эта область на уровне клиента позволяет администратору пользователей использовать свои привилегии для всех пользователей в клиенте, за исключением пользователей с более высоким уровнем привилегий, таких как глобальный администратор.
POST https://graph.microsoft.com/v1.0/roleManagement/directory/roleEligibilityScheduleRequests
Content-type: application/json
{
"action": "AdminAssign",
"justification": "Assign User Admin eligibility to IT Helpdesk (User) group",
"roleDefinitionId": "fe930be7-5e62-47db-91af-98c3a49a38b1",
"directoryScopeId": "/",
"principalId": "e77cbb23-0ff2-4e18-819c-690f58269752",
"scheduleInfo": {
"startDateTime": "2021-07-01T00:00:00Z",
"expiration": {
"endDateTime": "2022-06-30T00:00:00Z",
"type": "AfterDateTime"
}
}
}
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.Models;
var requestBody = new UnifiedRoleEligibilityScheduleRequest
{
Action = UnifiedRoleScheduleRequestActions.AdminAssign,
Justification = "Assign User Admin eligibility to IT Helpdesk (User) group",
RoleDefinitionId = "fe930be7-5e62-47db-91af-98c3a49a38b1",
DirectoryScopeId = "/",
PrincipalId = "e77cbb23-0ff2-4e18-819c-690f58269752",
ScheduleInfo = new RequestSchedule
{
StartDateTime = DateTimeOffset.Parse("2021-07-01T00:00:00Z"),
Expiration = new ExpirationPattern
{
EndDateTime = DateTimeOffset.Parse("2022-06-30T00:00:00Z"),
Type = ExpirationPatternType.AfterDateTime,
},
},
};
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.RoleManagement.Directory.RoleEligibilityScheduleRequests.PostAsync(requestBody);
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
UnifiedRoleEligibilityScheduleRequest unifiedRoleEligibilityScheduleRequest = new UnifiedRoleEligibilityScheduleRequest();
unifiedRoleEligibilityScheduleRequest.setAction(UnifiedRoleScheduleRequestActions.AdminAssign);
unifiedRoleEligibilityScheduleRequest.setJustification("Assign User Admin eligibility to IT Helpdesk (User) group");
unifiedRoleEligibilityScheduleRequest.setRoleDefinitionId("fe930be7-5e62-47db-91af-98c3a49a38b1");
unifiedRoleEligibilityScheduleRequest.setDirectoryScopeId("/");
unifiedRoleEligibilityScheduleRequest.setPrincipalId("e77cbb23-0ff2-4e18-819c-690f58269752");
RequestSchedule scheduleInfo = new RequestSchedule();
OffsetDateTime startDateTime = OffsetDateTime.parse("2021-07-01T00:00:00Z");
scheduleInfo.setStartDateTime(startDateTime);
ExpirationPattern expiration = new ExpirationPattern();
OffsetDateTime endDateTime = OffsetDateTime.parse("2022-06-30T00:00:00Z");
expiration.setEndDateTime(endDateTime);
expiration.setType(ExpirationPatternType.AfterDateTime);
scheduleInfo.setExpiration(expiration);
unifiedRoleEligibilityScheduleRequest.setScheduleInfo(scheduleInfo);
UnifiedRoleEligibilityScheduleRequest result = graphClient.roleManagement().directory().roleEligibilityScheduleRequests().post(unifiedRoleEligibilityScheduleRequest);
<?php
use Microsoft\Graph\GraphServiceClient;
use Microsoft\Graph\Generated\Models\UnifiedRoleEligibilityScheduleRequest;
use Microsoft\Graph\Generated\Models\UnifiedRoleScheduleRequestActions;
use Microsoft\Graph\Generated\Models\RequestSchedule;
use Microsoft\Graph\Generated\Models\ExpirationPattern;
use Microsoft\Graph\Generated\Models\ExpirationPatternType;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestBody = new UnifiedRoleEligibilityScheduleRequest();
$requestBody->setAction(new UnifiedRoleScheduleRequestActions('adminAssign'));
$requestBody->setJustification('Assign User Admin eligibility to IT Helpdesk (User) group');
$requestBody->setRoleDefinitionId('fe930be7-5e62-47db-91af-98c3a49a38b1');
$requestBody->setDirectoryScopeId('/');
$requestBody->setPrincipalId('e77cbb23-0ff2-4e18-819c-690f58269752');
$scheduleInfo = new RequestSchedule();
$scheduleInfo->setStartDateTime(new \DateTime('2021-07-01T00:00:00Z'));
$scheduleInfoExpiration = new ExpirationPattern();
$scheduleInfoExpiration->setEndDateTime(new \DateTime('2022-06-30T00:00:00Z'));
$scheduleInfoExpiration->setType(new ExpirationPatternType('afterDateTime'));
$scheduleInfo->setExpiration($scheduleInfoExpiration);
$requestBody->setScheduleInfo($scheduleInfo);
$result = $graphServiceClient->roleManagement()->directory()->roleEligibilityScheduleRequests()->post($requestBody)->wait();
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.models.unified_role_eligibility_schedule_request import UnifiedRoleEligibilityScheduleRequest
from msgraph.generated.models.unified_role_schedule_request_actions import UnifiedRoleScheduleRequestActions
from msgraph.generated.models.request_schedule import RequestSchedule
from msgraph.generated.models.expiration_pattern import ExpirationPattern
from msgraph.generated.models.expiration_pattern_type import ExpirationPatternType
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
request_body = UnifiedRoleEligibilityScheduleRequest(
action = UnifiedRoleScheduleRequestActions.AdminAssign,
justification = "Assign User Admin eligibility to IT Helpdesk (User) group",
role_definition_id = "fe930be7-5e62-47db-91af-98c3a49a38b1",
directory_scope_id = "/",
principal_id = "e77cbb23-0ff2-4e18-819c-690f58269752",
schedule_info = RequestSchedule(
start_date_time = "2021-07-01T00:00:00Z",
expiration = ExpirationPattern(
end_date_time = "2022-06-30T00:00:00Z",
type = ExpirationPatternType.AfterDateTime,
),
),
)
result = await graph_client.role_management.directory.role_eligibility_schedule_requests.post(request_body)
Хотя участники группы теперь имеют право на роль администратора пользователей, они по-прежнему не могут использовать роль, если они не активируют роль явным образом. Вы можете подтвердить, проверив текущие назначения ролей пользователя.
GET https://graph.microsoft.com/v1.0/roleManagement/directory/roleAssignments?$filter=principalId eq '7146daa8-1b4b-4a66-b2f7-cf593d03c8d2'
// Code snippets are only available for the latest version. Current version is 5.x
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.RoleManagement.Directory.RoleAssignments.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Filter = "principalId eq '7146daa8-1b4b-4a66-b2f7-cf593d03c8d2'";
});
// Code snippets are only available for the latest major version. Current major version is $v1.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
graphrolemanagement "github.com/microsoftgraph/msgraph-sdk-go/rolemanagement"
//other-imports
)
requestFilter := "principalId eq '7146daa8-1b4b-4a66-b2f7-cf593d03c8d2'"
requestParameters := &graphrolemanagement.DirectoryRoleAssignmentsRequestBuilderGetQueryParameters{
Filter: &requestFilter,
}
configuration := &graphrolemanagement.DirectoryRoleAssignmentsRequestBuilderGetRequestConfiguration{
QueryParameters: requestParameters,
}
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
roleAssignments, err := graphClient.RoleManagement().Directory().RoleAssignments().Get(context.Background(), configuration)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
UnifiedRoleAssignmentCollectionResponse result = graphClient.roleManagement().directory().roleAssignments().get(requestConfiguration -> {
requestConfiguration.queryParameters.filter = "principalId eq '7146daa8-1b4b-4a66-b2f7-cf593d03c8d2'";
});
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.role_management.directory.role_assignments.role_assignments_request_builder import RoleAssignmentsRequestBuilder
from kiota_abstractions.base_request_configuration import RequestConfiguration
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
query_params = RoleAssignmentsRequestBuilder.RoleAssignmentsRequestBuilderGetQueryParameters(
filter = "principalId eq '7146daa8-1b4b-4a66-b2f7-cf593d03c8d2'",
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
result = await graph_client.role_management.directory.role_assignments.get(request_configuration = request_configuration)
Пустой объект ответа показывает, что у пользователя нет ролей Microsoft Entra в Contoso. Теперь пользователь будет активировать свою доступную роль администратора пользователей в течение ограниченного времени.
Шаг 4. Пользователь самостоятельно активирует соответствующее назначение
Запрос на инциденты CONTOSO: Security-012345 был поднят в системе управления инцидентами Contoso, и компания требует, чтобы все маркеры обновления сотрудников были признаны недействительными. Как участник службы ИТ-поддержки, Aline отвечает за выполнение этой задачи.
Сначала запустите приложение Authenticator на телефоне и откройте учетную запись Aline Dupuy.
Войдите в Graph Обозреватель как Aline. Для этого шага можно использовать другой браузер. Это не приведет к прерыванию текущего сеанса. Кроме того, можно прервать текущий сеанс, выйдя из Graph Обозреватель и войдите в систему как Aline.
После входа активируйте роль администратора пользователей в течение пяти часов.
Запрос
Чтобы активировать роль, вызовите конечную точку roleAssignmentScheduleRequests . В этом запросе UserActivate действие позволяет активировать соответствующее назначение.
Для principalId укажите значение идентификатора (Aline).
RoleDefinitionId — это идентификатор роли, на которую вы имеете право, в данном случае — роль администратора пользователей.
Введите сведения о системе билетов, которая предоставляет проверяемое обоснование для активации запроса.
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.Models;
var requestBody = new UnifiedRoleAssignmentScheduleRequest
{
Action = UnifiedRoleScheduleRequestActions.SelfActivate,
PrincipalId = "7146daa8-1b4b-4a66-b2f7-cf593d03c8d2",
RoleDefinitionId = "fe930be7-5e62-47db-91af-98c3a49a38b1",
DirectoryScopeId = "/",
Justification = "Need to invalidate all app refresh tokens for Contoso users.",
ScheduleInfo = new RequestSchedule
{
StartDateTime = DateTimeOffset.Parse("2024-03-25T15:13:00.000Z"),
Expiration = new ExpirationPattern
{
Type = ExpirationPatternType.AfterDuration,
Duration = TimeSpan.Parse("PT5H"),
},
},
TicketInfo = new TicketInfo
{
TicketNumber = "CONTOSO:Security-012345",
TicketSystem = "Contoso ICM",
},
};
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.RoleManagement.Directory.RoleAssignmentScheduleRequests.PostAsync(requestBody);
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
UnifiedRoleAssignmentScheduleRequest unifiedRoleAssignmentScheduleRequest = new UnifiedRoleAssignmentScheduleRequest();
unifiedRoleAssignmentScheduleRequest.setAction(UnifiedRoleScheduleRequestActions.SelfActivate);
unifiedRoleAssignmentScheduleRequest.setPrincipalId("7146daa8-1b4b-4a66-b2f7-cf593d03c8d2");
unifiedRoleAssignmentScheduleRequest.setRoleDefinitionId("fe930be7-5e62-47db-91af-98c3a49a38b1");
unifiedRoleAssignmentScheduleRequest.setDirectoryScopeId("/");
unifiedRoleAssignmentScheduleRequest.setJustification("Need to invalidate all app refresh tokens for Contoso users.");
RequestSchedule scheduleInfo = new RequestSchedule();
OffsetDateTime startDateTime = OffsetDateTime.parse("2024-03-25T15:13:00.000Z");
scheduleInfo.setStartDateTime(startDateTime);
ExpirationPattern expiration = new ExpirationPattern();
expiration.setType(ExpirationPatternType.AfterDuration);
PeriodAndDuration duration = PeriodAndDuration.ofDuration(Duration.parse("PT5H"));
expiration.setDuration(duration);
scheduleInfo.setExpiration(expiration);
unifiedRoleAssignmentScheduleRequest.setScheduleInfo(scheduleInfo);
TicketInfo ticketInfo = new TicketInfo();
ticketInfo.setTicketNumber("CONTOSO:Security-012345");
ticketInfo.setTicketSystem("Contoso ICM");
unifiedRoleAssignmentScheduleRequest.setTicketInfo(ticketInfo);
UnifiedRoleAssignmentScheduleRequest result = graphClient.roleManagement().directory().roleAssignmentScheduleRequests().post(unifiedRoleAssignmentScheduleRequest);
<?php
use Microsoft\Graph\GraphServiceClient;
use Microsoft\Graph\Generated\Models\UnifiedRoleAssignmentScheduleRequest;
use Microsoft\Graph\Generated\Models\UnifiedRoleScheduleRequestActions;
use Microsoft\Graph\Generated\Models\RequestSchedule;
use Microsoft\Graph\Generated\Models\ExpirationPattern;
use Microsoft\Graph\Generated\Models\ExpirationPatternType;
use Microsoft\Graph\Generated\Models\TicketInfo;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestBody = new UnifiedRoleAssignmentScheduleRequest();
$requestBody->setAction(new UnifiedRoleScheduleRequestActions('selfActivate'));
$requestBody->setPrincipalId('7146daa8-1b4b-4a66-b2f7-cf593d03c8d2');
$requestBody->setRoleDefinitionId('fe930be7-5e62-47db-91af-98c3a49a38b1');
$requestBody->setDirectoryScopeId('/');
$requestBody->setJustification('Need to invalidate all app refresh tokens for Contoso users.');
$scheduleInfo = new RequestSchedule();
$scheduleInfo->setStartDateTime(new \DateTime('2024-03-25T15:13:00.000Z'));
$scheduleInfoExpiration = new ExpirationPattern();
$scheduleInfoExpiration->setType(new ExpirationPatternType('afterDuration'));
$scheduleInfoExpiration->setDuration(new \DateInterval('PT5H'));
$scheduleInfo->setExpiration($scheduleInfoExpiration);
$requestBody->setScheduleInfo($scheduleInfo);
$ticketInfo = new TicketInfo();
$ticketInfo->setTicketNumber('CONTOSO:Security-012345');
$ticketInfo->setTicketSystem('Contoso ICM');
$requestBody->setTicketInfo($ticketInfo);
$result = $graphServiceClient->roleManagement()->directory()->roleAssignmentScheduleRequests()->post($requestBody)->wait();
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.models.unified_role_assignment_schedule_request import UnifiedRoleAssignmentScheduleRequest
from msgraph.generated.models.unified_role_schedule_request_actions import UnifiedRoleScheduleRequestActions
from msgraph.generated.models.request_schedule import RequestSchedule
from msgraph.generated.models.expiration_pattern import ExpirationPattern
from msgraph.generated.models.expiration_pattern_type import ExpirationPatternType
from msgraph.generated.models.ticket_info import TicketInfo
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
request_body = UnifiedRoleAssignmentScheduleRequest(
action = UnifiedRoleScheduleRequestActions.SelfActivate,
principal_id = "7146daa8-1b4b-4a66-b2f7-cf593d03c8d2",
role_definition_id = "fe930be7-5e62-47db-91af-98c3a49a38b1",
directory_scope_id = "/",
justification = "Need to invalidate all app refresh tokens for Contoso users.",
schedule_info = RequestSchedule(
start_date_time = "2024-03-25T15:13:00.000Z",
expiration = ExpirationPattern(
type = ExpirationPatternType.AfterDuration,
duration = "PT5H",
),
),
ticket_info = TicketInfo(
ticket_number = "CONTOSO:Security-012345",
ticket_system = "Contoso ICM",
),
)
result = await graph_client.role_management.directory.role_assignment_schedule_requests.post(request_body)
Вы можете подтвердить назначение, запустив GET https://graph.microsoft.com/v1.0/roleManagement/directory/roleAssignmentScheduleRequests/filterByCurrentUser(on='principal'). Объект ответа возвращает только что активированное назначение роли с состоянием Granted. С вашей новой привилегией выполняйте все разрешенные действия в течение пяти часов, для выполнения задания. По истечении пяти часов срок действия активного назначения истекает, но благодаря вашему членству в группе ИТ-поддержки (пользователи) вы получите право на роль администратора пользователей.
Шаг 6. Очистка ресурсов
Войдите как администратор привилегированных ролей и удалите следующие ресурсы, созданные для этого руководства: запрос на участие в роли и группу ИТ-поддержки (пользователи).
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.Models;
var requestBody = new UnifiedRoleEligibilityScheduleRequest
{
Action = UnifiedRoleScheduleRequestActions.AdminRemove,
PrincipalId = "e77cbb23-0ff2-4e18-819c-690f58269752",
RoleDefinitionId = "fe930be7-5e62-47db-91af-98c3a49a38b1",
DirectoryScopeId = "/",
};
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.RoleManagement.Directory.RoleEligibilityScheduleRequests.PostAsync(requestBody);
// Code snippets are only available for the latest major version. Current major version is $v1.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
graphmodels "github.com/microsoftgraph/msgraph-sdk-go/models"
//other-imports
)
requestBody := graphmodels.NewUnifiedRoleEligibilityScheduleRequest()
action := graphmodels.ADMINREMOVE_UNIFIEDROLESCHEDULEREQUESTACTIONS
requestBody.SetAction(&action)
principalId := "e77cbb23-0ff2-4e18-819c-690f58269752"
requestBody.SetPrincipalId(&principalId)
roleDefinitionId := "fe930be7-5e62-47db-91af-98c3a49a38b1"
requestBody.SetRoleDefinitionId(&roleDefinitionId)
directoryScopeId := "/"
requestBody.SetDirectoryScopeId(&directoryScopeId)
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
roleEligibilityScheduleRequests, err := graphClient.RoleManagement().Directory().RoleEligibilityScheduleRequests().Post(context.Background(), requestBody, nil)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
UnifiedRoleEligibilityScheduleRequest unifiedRoleEligibilityScheduleRequest = new UnifiedRoleEligibilityScheduleRequest();
unifiedRoleEligibilityScheduleRequest.setAction(UnifiedRoleScheduleRequestActions.AdminRemove);
unifiedRoleEligibilityScheduleRequest.setPrincipalId("e77cbb23-0ff2-4e18-819c-690f58269752");
unifiedRoleEligibilityScheduleRequest.setRoleDefinitionId("fe930be7-5e62-47db-91af-98c3a49a38b1");
unifiedRoleEligibilityScheduleRequest.setDirectoryScopeId("/");
UnifiedRoleEligibilityScheduleRequest result = graphClient.roleManagement().directory().roleEligibilityScheduleRequests().post(unifiedRoleEligibilityScheduleRequest);
<?php
use Microsoft\Graph\GraphServiceClient;
use Microsoft\Graph\Generated\Models\UnifiedRoleEligibilityScheduleRequest;
use Microsoft\Graph\Generated\Models\UnifiedRoleScheduleRequestActions;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestBody = new UnifiedRoleEligibilityScheduleRequest();
$requestBody->setAction(new UnifiedRoleScheduleRequestActions('adminRemove'));
$requestBody->setPrincipalId('e77cbb23-0ff2-4e18-819c-690f58269752');
$requestBody->setRoleDefinitionId('fe930be7-5e62-47db-91af-98c3a49a38b1');
$requestBody->setDirectoryScopeId('/');
$result = $graphServiceClient->roleManagement()->directory()->roleEligibilityScheduleRequests()->post($requestBody)->wait();
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.models.unified_role_eligibility_schedule_request import UnifiedRoleEligibilityScheduleRequest
from msgraph.generated.models.unified_role_schedule_request_actions import UnifiedRoleScheduleRequestActions
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
request_body = UnifiedRoleEligibilityScheduleRequest(
action = UnifiedRoleScheduleRequestActions.AdminRemove,
principal_id = "e77cbb23-0ff2-4e18-819c-690f58269752",
role_definition_id = "fe930be7-5e62-47db-91af-98c3a49a38b1",
directory_scope_id = "/",
)
result = await graph_client.role_management.directory.role_eligibility_schedule_requests.post(request_body)
// Code snippets are only available for the latest version. Current version is 5.x
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
await graphClient.Groups["{group-id}"].DeleteAsync();
// Code snippets are only available for the latest major version. Current major version is $v1.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
//other-imports
)
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
graphClient.Groups().ByGroupId("group-id").Delete(context.Background(), nil)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
graphClient.groups().byGroupId("{group-id}").delete();
<?php
use Microsoft\Graph\GraphServiceClient;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$graphServiceClient->groups()->byGroupId('group-id')->delete()->wait();
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
await graph_client.groups.by_group_id('group-id').delete()
В этом руководстве вы узнали, как управлять назначениями административных ролей в Microsoft Entra ID с помощью API PIM.
Хотя вы сделали группу правой на роль администратора, вы можете также назначить активную роль группе и сделать ее участников право на нее. В этом сценарии используйте PIM для API групп.
Для активации роли тестового пользователя требуется многофакторная проверка подлинности. Это требование является частью параметров роли Microsoft Entra, и вы можете изменить правила, чтобы не требовать многофакторной проверки подлинности.
В рамках настраиваемых правил можно также настроить следующие параметры:
Ограничьте максимально допустимую длительность активации роли.
Требовать или не требовать обоснование и сведения о билете для активации роли.