Identificación y corrección de riesgos mediante las API de protección de identidades
Artículo
Protección de Microsoft Entra ID proporciona a las organizaciones información sobre el riesgo basado en identidades y diferentes formas de investigar y corregir automáticamente el riesgo. Las API de Identity Protection usadas en este tutorial pueden ayudarle a identificar los riesgos y configurar un flujo de trabajo para confirmar el riesgo o habilitar la corrección.
En este tutorial, aprenderá a usar las API de protección de identidades para:
Genere un inicio de sesión de riesgo.
Permitir que los usuarios con inicios de sesión de riesgo corrijan el estado de riesgo con una directiva de acceso condicional que requiera autenticación multifactor (MFA).
Impedir que un usuario inicie sesión con una directiva de acceso condicional.
Descartar un riesgo de usuario.
Requisitos previos
Para completar este tutorial, necesita los siguientes recursos y privilegios:
Un inquilino de Microsoft Entra en funcionamiento con una licencia P1 o P2 de Microsoft Entra ID.
Inicie sesión en un cliente de API, como Graph Explorer , con una cuenta que tenga al menos el rol de administrador de acceso condicional .
Concédese los siguientes permisos delegados: IdentityRiskEvent.Read.All, IdentityRiskyUser.ReadWrite.All, Policy.Read.All, Policy.ReadWrite.ConditionalAccessy User.ReadWrite.All.
Una cuenta de usuario de prueba que se usa para iniciar sesión más adelante en una sesión anónima para desencadenar una detección de riesgos. Puede usar una sesión de exploración privada o el explorador Tor. En este tutorial, el alias de correo de usuario de prueba es MyTestUser1.
Paso 1: Desencadenar una detección de riesgos
En la sesión anónima del explorador, inicie sesión como MyTestUser1 para entra.microsoft.com.
Paso 2: Enumerar detecciones de riesgos
Cuando MyTestUser1 inició sesión en el Centro de administración Microsoft Entra mediante el explorador anónimo, se detectó un anonymizedIPAddress evento de riesgo. Puede usar el parámetro de $filter consulta para obtener solo las detecciones de riesgo asociadas a la cuenta de usuario MyTestUser1 . El evento puede tardar unos minutos en devolverse.
GET https://graph.microsoft.com/v1.0/identityProtection/riskDetections?$filter=userDisplayName eq 'MyTestUser1'
// 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.IdentityProtection.RiskDetections.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Filter = "userDisplayName eq 'MyTestUser1'";
});
// 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"
graphidentityprotection "github.com/microsoftgraph/msgraph-sdk-go/identityprotection"
//other-imports
)
requestFilter := "userDisplayName eq 'MyTestUser1'"
requestParameters := &graphidentityprotection.IdentityProtectionRiskDetectionsRequestBuilderGetQueryParameters{
Filter: &requestFilter,
}
configuration := &graphidentityprotection.IdentityProtectionRiskDetectionsRequestBuilderGetRequestConfiguration{
QueryParameters: requestParameters,
}
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
riskDetections, err := graphClient.IdentityProtection().RiskDetections().Get(context.Background(), configuration)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
RiskDetectionCollectionResponse result = graphClient.identityProtection().riskDetections().get(requestConfiguration -> {
requestConfiguration.queryParameters.filter = "userDisplayName eq 'MyTestUser1'";
});
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.identity_protection.risk_detections.risk_detections_request_builder import RiskDetectionsRequestBuilder
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 = RiskDetectionsRequestBuilder.RiskDetectionsRequestBuilderGetQueryParameters(
filter = "userDisplayName eq 'MyTestUser1'",
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
result = await graph_client.identity_protection.risk_detections.get(request_configuration = request_configuration)
Puede usar directivas de acceso condicional en su organización para permitir que los usuarios puedan corregirse automáticamente cuando se detecte riesgo. La corrección automática permite a los usuarios desbloquearse a sí mismos para acceder a sus recursos de forma segura después de completar la solicitud de directiva. En este paso, creará una directiva de acceso condicional que requiere que el usuario inicie sesión con MFA si se produce una detección de riesgo medio o alto.
Configurar la autenticación multifactor
Al configurar una cuenta para MFA, puede elegir entre varios métodos para autenticar al usuario. Elija el mejor método para su situación para completar este tutorial.
Complete el procedimiento de configuración de MFA con el método adecuado para su situación, como el uso de la aplicación Microsoft Authenticator.
Creación de la directiva de acceso condicional
La directiva de acceso condicional permite establecer las condiciones de la directiva para identificar los niveles de riesgo de inicio de sesión. Los niveles de riesgo pueden ser low, medium, high, none. En el ejemplo siguiente se muestra cómo requerir MFA para los inicios de sesión con niveles de riesgo medio y alto.
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.Models;
var requestBody = new ConditionalAccessPolicy
{
DisplayName = "Policy for risky sign-in",
State = ConditionalAccessPolicyState.Enabled,
Conditions = new ConditionalAccessConditionSet
{
SignInRiskLevels = new List<RiskLevel?>
{
RiskLevel.High,
RiskLevel.Medium,
},
Applications = new ConditionalAccessApplications
{
IncludeApplications = new List<string>
{
"All",
},
},
Users = new ConditionalAccessUsers
{
IncludeUsers = new List<string>
{
"4628e7df-dff3-407c-a08f-75f08c0806dc",
},
},
},
GrantControls = new ConditionalAccessGrantControls
{
Operator = "OR",
BuiltInControls = new List<ConditionalAccessGrantControl?>
{
ConditionalAccessGrantControl.Mfa,
},
},
};
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Identity.ConditionalAccess.Policies.PostAsync(requestBody);
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
ConditionalAccessPolicy conditionalAccessPolicy = new ConditionalAccessPolicy();
conditionalAccessPolicy.setDisplayName("Policy for risky sign-in");
conditionalAccessPolicy.setState(ConditionalAccessPolicyState.Enabled);
ConditionalAccessConditionSet conditions = new ConditionalAccessConditionSet();
LinkedList<RiskLevel> signInRiskLevels = new LinkedList<RiskLevel>();
signInRiskLevels.add(RiskLevel.High);
signInRiskLevels.add(RiskLevel.Medium);
conditions.setSignInRiskLevels(signInRiskLevels);
ConditionalAccessApplications applications = new ConditionalAccessApplications();
LinkedList<String> includeApplications = new LinkedList<String>();
includeApplications.add("All");
applications.setIncludeApplications(includeApplications);
conditions.setApplications(applications);
ConditionalAccessUsers users = new ConditionalAccessUsers();
LinkedList<String> includeUsers = new LinkedList<String>();
includeUsers.add("4628e7df-dff3-407c-a08f-75f08c0806dc");
users.setIncludeUsers(includeUsers);
conditions.setUsers(users);
conditionalAccessPolicy.setConditions(conditions);
ConditionalAccessGrantControls grantControls = new ConditionalAccessGrantControls();
grantControls.setOperator("OR");
LinkedList<ConditionalAccessGrantControl> builtInControls = new LinkedList<ConditionalAccessGrantControl>();
builtInControls.add(ConditionalAccessGrantControl.Mfa);
grantControls.setBuiltInControls(builtInControls);
conditionalAccessPolicy.setGrantControls(grantControls);
ConditionalAccessPolicy result = graphClient.identity().conditionalAccess().policies().post(conditionalAccessPolicy);
<?php
use Microsoft\Graph\GraphServiceClient;
use Microsoft\Graph\Generated\Models\ConditionalAccessPolicy;
use Microsoft\Graph\Generated\Models\ConditionalAccessPolicyState;
use Microsoft\Graph\Generated\Models\ConditionalAccessConditionSet;
use Microsoft\Graph\Generated\Models\RiskLevel;
use Microsoft\Graph\Generated\Models\ConditionalAccessApplications;
use Microsoft\Graph\Generated\Models\ConditionalAccessUsers;
use Microsoft\Graph\Generated\Models\ConditionalAccessGrantControls;
use Microsoft\Graph\Generated\Models\ConditionalAccessGrantControl;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestBody = new ConditionalAccessPolicy();
$requestBody->setDisplayName('Policy for risky sign-in');
$requestBody->setState(new ConditionalAccessPolicyState('enabled'));
$conditions = new ConditionalAccessConditionSet();
$conditions->setSignInRiskLevels([new RiskLevel('high'),new RiskLevel('medium'), ]);
$conditionsApplications = new ConditionalAccessApplications();
$conditionsApplications->setIncludeApplications(['All', ]);
$conditions->setApplications($conditionsApplications);
$conditionsUsers = new ConditionalAccessUsers();
$conditionsUsers->setIncludeUsers(['4628e7df-dff3-407c-a08f-75f08c0806dc', ]);
$conditions->setUsers($conditionsUsers);
$requestBody->setConditions($conditions);
$grantControls = new ConditionalAccessGrantControls();
$grantControls->setOperator('OR');
$grantControls->setBuiltInControls([new ConditionalAccessGrantControl('mfa'), ]);
$requestBody->setGrantControls($grantControls);
$result = $graphServiceClient->identity()->conditionalAccess()->policies()->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.conditional_access_policy import ConditionalAccessPolicy
from msgraph.generated.models.conditional_access_policy_state import ConditionalAccessPolicyState
from msgraph.generated.models.conditional_access_condition_set import ConditionalAccessConditionSet
from msgraph.generated.models.risk_level import RiskLevel
from msgraph.generated.models.conditional_access_applications import ConditionalAccessApplications
from msgraph.generated.models.conditional_access_users import ConditionalAccessUsers
from msgraph.generated.models.conditional_access_grant_controls import ConditionalAccessGrantControls
from msgraph.generated.models.conditional_access_grant_control import ConditionalAccessGrantControl
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
request_body = ConditionalAccessPolicy(
display_name = "Policy for risky sign-in",
state = ConditionalAccessPolicyState.Enabled,
conditions = ConditionalAccessConditionSet(
sign_in_risk_levels = [
RiskLevel.High,
RiskLevel.Medium,
],
applications = ConditionalAccessApplications(
include_applications = [
"All",
],
),
users = ConditionalAccessUsers(
include_users = [
"4628e7df-dff3-407c-a08f-75f08c0806dc",
],
),
),
grant_controls = ConditionalAccessGrantControls(
operator = "OR",
built_in_controls = [
ConditionalAccessGrantControl.Mfa,
],
),
)
result = await graph_client.identity.conditional_access.policies.post(request_body)
Paso 4: Desencadenar otro inicio de sesión de riesgo pero completar la autenticación multifactor
Al iniciar sesión en el explorador anónimo, se detectó un riesgo, pero lo corrigió completando MFA.
Inicie sesión en entra.microsoft.com con la cuenta MyTestUser1 y complete el proceso de MFA.
Paso 5: Enumerar detecciones de riesgo
Vuelva a ejecutar la solicitud en el paso 2 para obtener la detección de riesgos más reciente para la cuenta de usuario MyTestUser1 . Dado que MFA se completó en el paso 4, riskState para este evento de inicio de sesión más reciente ahora remediatedes .
[Opcional] Impedir que el usuario inicie sesión
En lugar de proporcionar al usuario la oportunidad de corregirse automáticamente, puede impedir que el usuario que está asociado a un inicio de sesión de riesgo inicie sesión. En este paso, creará una nueva directiva de acceso condicional que impide que el usuario inicie sesión si se produce una detección de riesgo medio o alto. La diferencia entre esta directiva y la directiva de versión preliminar en el paso 3 es que builtInControls ahora está establecido en block.
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.Models;
var requestBody = new ConditionalAccessPolicy
{
DisplayName = "Policy for risky sign-in block access",
State = ConditionalAccessPolicyState.Enabled,
Conditions = new ConditionalAccessConditionSet
{
SignInRiskLevels = new List<RiskLevel?>
{
RiskLevel.High,
RiskLevel.Medium,
},
Applications = new ConditionalAccessApplications
{
IncludeApplications = new List<string>
{
"All",
},
},
Users = new ConditionalAccessUsers
{
IncludeUsers = new List<string>
{
"4628e7df-dff3-407c-a08f-75f08c0806dc",
},
},
},
GrantControls = new ConditionalAccessGrantControls
{
Operator = "OR",
BuiltInControls = new List<ConditionalAccessGrantControl?>
{
ConditionalAccessGrantControl.Block,
},
},
};
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Identity.ConditionalAccess.Policies.PostAsync(requestBody);
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
ConditionalAccessPolicy conditionalAccessPolicy = new ConditionalAccessPolicy();
conditionalAccessPolicy.setDisplayName("Policy for risky sign-in block access");
conditionalAccessPolicy.setState(ConditionalAccessPolicyState.Enabled);
ConditionalAccessConditionSet conditions = new ConditionalAccessConditionSet();
LinkedList<RiskLevel> signInRiskLevels = new LinkedList<RiskLevel>();
signInRiskLevels.add(RiskLevel.High);
signInRiskLevels.add(RiskLevel.Medium);
conditions.setSignInRiskLevels(signInRiskLevels);
ConditionalAccessApplications applications = new ConditionalAccessApplications();
LinkedList<String> includeApplications = new LinkedList<String>();
includeApplications.add("All");
applications.setIncludeApplications(includeApplications);
conditions.setApplications(applications);
ConditionalAccessUsers users = new ConditionalAccessUsers();
LinkedList<String> includeUsers = new LinkedList<String>();
includeUsers.add("4628e7df-dff3-407c-a08f-75f08c0806dc");
users.setIncludeUsers(includeUsers);
conditions.setUsers(users);
conditionalAccessPolicy.setConditions(conditions);
ConditionalAccessGrantControls grantControls = new ConditionalAccessGrantControls();
grantControls.setOperator("OR");
LinkedList<ConditionalAccessGrantControl> builtInControls = new LinkedList<ConditionalAccessGrantControl>();
builtInControls.add(ConditionalAccessGrantControl.Block);
grantControls.setBuiltInControls(builtInControls);
conditionalAccessPolicy.setGrantControls(grantControls);
ConditionalAccessPolicy result = graphClient.identity().conditionalAccess().policies().post(conditionalAccessPolicy);
<?php
use Microsoft\Graph\GraphServiceClient;
use Microsoft\Graph\Generated\Models\ConditionalAccessPolicy;
use Microsoft\Graph\Generated\Models\ConditionalAccessPolicyState;
use Microsoft\Graph\Generated\Models\ConditionalAccessConditionSet;
use Microsoft\Graph\Generated\Models\RiskLevel;
use Microsoft\Graph\Generated\Models\ConditionalAccessApplications;
use Microsoft\Graph\Generated\Models\ConditionalAccessUsers;
use Microsoft\Graph\Generated\Models\ConditionalAccessGrantControls;
use Microsoft\Graph\Generated\Models\ConditionalAccessGrantControl;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestBody = new ConditionalAccessPolicy();
$requestBody->setDisplayName('Policy for risky sign-in block access');
$requestBody->setState(new ConditionalAccessPolicyState('enabled'));
$conditions = new ConditionalAccessConditionSet();
$conditions->setSignInRiskLevels([new RiskLevel('high'),new RiskLevel('medium'), ]);
$conditionsApplications = new ConditionalAccessApplications();
$conditionsApplications->setIncludeApplications(['All', ]);
$conditions->setApplications($conditionsApplications);
$conditionsUsers = new ConditionalAccessUsers();
$conditionsUsers->setIncludeUsers(['4628e7df-dff3-407c-a08f-75f08c0806dc', ]);
$conditions->setUsers($conditionsUsers);
$requestBody->setConditions($conditions);
$grantControls = new ConditionalAccessGrantControls();
$grantControls->setOperator('OR');
$grantControls->setBuiltInControls([new ConditionalAccessGrantControl('block'), ]);
$requestBody->setGrantControls($grantControls);
$result = $graphServiceClient->identity()->conditionalAccess()->policies()->post($requestBody)->wait();
Con esta directiva de acceso condicional en vigor, la cuenta MyTestUser1 ahora está bloqueada para iniciar sesión porque el nivel de riesgo de inicio de sesión es medium o high.
Paso 6: Descartar usuarios de riesgo
Si cree que el usuario no está en riesgo y no quiere aplicar una directiva de acceso condicional, puede descartar manualmente al usuario de riesgo. La solicitud devuelve una 204 No Content respuesta.
POST https://graph.microsoft.com/v1.0/identityProtection/riskyUsers/dismiss
Content-Type: application/json
{
"userIds": [
"4628e7df-dff3-407c-a08f-75f08c0806dc"
]
}
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.IdentityProtection.RiskyUsers.Dismiss;
var requestBody = new DismissPostRequestBody
{
UserIds = new List<string>
{
"4628e7df-dff3-407c-a08f-75f08c0806dc",
},
};
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
await graphClient.IdentityProtection.RiskyUsers.Dismiss.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"
graphidentityprotection "github.com/microsoftgraph/msgraph-sdk-go/identityprotection"
//other-imports
)
requestBody := graphidentityprotection.NewDismissPostRequestBody()
userIds := []string {
"4628e7df-dff3-407c-a08f-75f08c0806dc",
}
requestBody.SetUserIds(userIds)
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
graphClient.IdentityProtection().RiskyUsers().Dismiss().Post(context.Background(), requestBody, nil)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
com.microsoft.graph.identityprotection.riskyusers.dismiss.DismissPostRequestBody dismissPostRequestBody = new com.microsoft.graph.identityprotection.riskyusers.dismiss.DismissPostRequestBody();
LinkedList<String> userIds = new LinkedList<String>();
userIds.add("4628e7df-dff3-407c-a08f-75f08c0806dc");
dismissPostRequestBody.setUserIds(userIds);
graphClient.identityProtection().riskyUsers().dismiss().post(dismissPostRequestBody);
<?php
use Microsoft\Graph\GraphServiceClient;
use Microsoft\Graph\Generated\IdentityProtection\RiskyUsers\Dismiss\DismissPostRequestBody;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestBody = new DismissPostRequestBody();
$requestBody->setUserIds(['4628e7df-dff3-407c-a08f-75f08c0806dc', ]);
$graphServiceClient->identityProtection()->riskyUsers()->dismiss()->post($requestBody)->wait();
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.identityprotection.riskyusers.dismiss.dismiss_post_request_body import DismissPostRequestBody
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
request_body = DismissPostRequestBody(
user_ids = [
"4628e7df-dff3-407c-a08f-75f08c0806dc",
],
)
await graph_client.identity_protection.risky_users.dismiss.post(request_body)
Después de descartar al usuario de riesgo, puede volver a ejecutar la solicitud en el paso 2 y observará que la cuenta de usuario MyTestUser1 ahora tiene un nivel de riesgo de none y un riskState de dismissed.
Paso 7: Limpiar los recursos
En este paso, eliminará las dos directivas de acceso condicional que ha creado. La solicitud devuelve una 204 No Content respuesta.
// 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.Identity.ConditionalAccess.Policies["{conditionalAccessPolicy-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.Identity().ConditionalAccess().Policies().ByConditionalAccessPolicyId("conditionalAccessPolicy-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.identity().conditionalAccess().policies().byConditionalAccessPolicyId("{conditionalAccessPolicy-id}").delete();
<?php
use Microsoft\Graph\GraphServiceClient;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$graphServiceClient->identity()->conditionalAccess()->policies()->byConditionalAccessPolicyId('conditionalAccessPolicy-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.identity.conditional_access.policies.by_conditional_access_policy_id('conditionalAccessPolicy-id').delete()