Código de colaboração B2B do Microsoft Entra e exemplos do PowerShell
Artigo
Exemplo do PowerShell
Você pode convidar usuários externos em massa para uma organização a partir de endereços de e-mail armazenados em um arquivo .csv.
Preparar o ficheiro .csv
Crie um novo arquivo .csv e nomeie-o invitations.csv. Neste exemplo, o ficheiro é guardado em C:\data e contém as seguintes informações:
Nome
InvitedUserEmailAddress
Gmail B2B Invitee
b2binvitee@gmail.com
Outlook B2B invitee
b2binvitee@outlook.com
Obtenha o Microsoft Graph PowerShell mais recente
Para usar os novos cmdlets, você deve instalar o módulo atualizado do Microsoft Graph PowerShell. Para obter mais informações, consulte Instalar o SDK do Microsoft Graph PowerShell
Iniciar sessão no seu inquilino
Connect-MgGraph -Scopes "User.Invite.All"
Executar o cmdlet do PowerShell
$invitations = import-csv C:\data\invitations.csv
$messageInfo = New-Object Microsoft.Open.MSGraph.Model.InvitedUserMessageInfo
$messageInfo.customizedMessageBody = "Hey there! Check this out. I created an invitation through PowerShell"
foreach ($email in $invitations) {
New-MgInvitation -InviteRedirectUrl "https://wingtiptoysonline-dev-ed.my.woodgrove.com" `
-InvitedUserDisplayName $email.Name -InvitedUserEmailAddress $email.InvitedUserEmailAddress `
-InvitedUserMessageInfo $messageInfo -SendInvitationMessage:$true
}
Este cmdlet envia um convite para os endereços de e-mail em convites.csv. Mais recursos desse cmdlet incluem:
Texto personalizado na mensagem de e-mail
Incluindo um nome a apresentar para o utilizador convidado
Envio de mensagens para os utilizadores no campo CC ou supressão de mensagens de e-mail
Exemplo de código
O exemplo de código ilustra como chamar a API de convite e obter a URL de resgate. Use o URL de resgate para enviar um e-mail de convite personalizado. Você pode compor o email com um cliente HTTP, para que possa personalizar sua aparência e enviá-lo por meio da API do Microsoft Graph.
using System;
using System.Threading.Tasks;
using Microsoft.Graph;
using Azure.Identity;
namespace SampleInviteApp
{
class Program
{
/// <summary>
/// This is the tenant ID of the tenant you want to invite users to.
/// </summary>
private static readonly string TenantID = "";
/// <summary>
/// This is the application id of the application that is registered in the above tenant.
/// </summary>
private static readonly string TestAppClientId = "";
/// <summary>
/// Client secret of the application.
/// </summary>
private static readonly string TestAppClientSecret = @"";
/// <summary>
/// This is the email address of the user you want to invite.
/// </summary>
private static readonly string InvitedUserEmailAddress = @"";
/// <summary>
/// This is the display name of the user you want to invite.
/// </summary>
private static readonly string InvitedUserDisplayName = @"";
/// <summary>
/// Main method.
/// </summary>
/// <param name="args">Optional arguments</param>
static async Task Main(string[] args)
{
string InviteRedeemUrl = await SendInvitation();
}
/// <summary>
/// Send the guest user invite request.
/// </summary>
private static async string SendInvitation()
{
/// Get the access token for our application to talk to Microsoft Graph.
var scopes = new[] { "https://graph.microsoft.com/.default" };
var clientSecretCredential = new ClientSecretCredential(TenantID, TestAppClientId, TestAppClientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
// Create the invitation object.
var invitation = new Invitation
{
InvitedUserEmailAddress = InvitedUserEmailAddress,
InvitedUserDisplayName = InvitedUserDisplayName,
InviteRedirectUrl = "https://www.microsoft.com",
SendInvitationMessage = true
};
// Send the invitation
var GraphResponse = await graphClient.Invitations
.Request()
.AddAsync(invitation);
// Return the invite redeem URL
return GraphResponse.InviteRedeemUrl;
}
}
}
const express = require('express')
const app = express()
const { Client } = require("@microsoft/microsoft-graph-client");
const { TokenCredentialAuthenticationProvider } = require("@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials");
const { ClientSecretCredential } = require("@azure/identity");
require("isomorphic-fetch");
// This is the application id of the application that is registered in the above tenant.
const CLIENT_ID = ""
// Client secret of the application.
const CLIENT_SECRET = ""
// This is the tenant ID of the tenant you want to invite users to. For example fabrikam.onmicrosoft.com
const TENANT_ID = ""
async function sendInvite() {
// Initialize a confidential client application. For more info, visit: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-a-service-principal-with-a-client-secret
const credential = new ClientSecretCredential(TENANT_ID, CLIENT_ID, CLIENT_SECRET);
// Initialize the Microsoft Graph authentication provider. For more info, visit: https://learn.microsoft.com/graph/sdks/choose-authentication-providers?tabs=Javascript#using--for-server-side-applications
const authProvider = new TokenCredentialAuthenticationProvider(credential, { scopes: ['https://graph.microsoft.com/.default'] });
// Create MS Graph client instance. For more info, visit: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/CreatingClientInstance.md
const client = Client.initWithMiddleware({
debugLogging: true,
authProvider,
});
// Create invitation object
const invitation = {
invitedUserEmailAddress: 'david@fabrikam.com',
invitedUserDisplayName: 'David',
inviteRedirectUrl: 'https://www.microsoft.com',
sendInvitationMessage: true
};
// Execute the MS Graph command. For more information, visit: https://learn.microsoft.com/graph/api/invitation-post
graphResponse = await client.api('/invitations')
.post(invitation);
// Return the invite redeem URL
return graphResponse.inviteRedeemUrl
}
const inviteRedeemUrl = await sendInvite();