Пространство имен: microsoft.graph
Важно!
API версии /beta в Microsoft Graph могут быть изменены. Использование этих API в производственных приложениях не поддерживается. Чтобы определить, доступен ли API в версии 1.0, используйте селектор версий.
Создайте пользователя. Если указать свойство @odata.type со значением с обязательными #microsoft.graph.agentUser свойствами, этот API создает объект agentUser .
Как минимум необходимо указать необходимые свойства. При необходимости вы можете указать другие записываемые свойства.
Эта операция по умолчанию возвращает только подмножество свойств для каждого пользователя и agentUser. Эти свойства по умолчанию указаны в разделе Свойства. Чтобы получить свойства, которые не возвращаются по умолчанию, выполните операцию GET и укажите их в параметре запроса OData $select.
Этот API доступен в следующих национальных облачных развертываниях.
| Глобальная служба |
Правительство США L4 |
Правительство США L5 (DOD) |
Китай управляется 21Vianet |
| ✅ |
✅ |
✅ |
✅ |
Разрешения
Выберите разрешение или разрешения, помеченные как наименее привилегированные для этого API. Используйте более привилегированное разрешение или разрешения только в том случае, если это требуется приложению. Дополнительные сведения о делегированных разрешениях и разрешениях приложений см. в разделе Типы разрешений. Дополнительные сведения об этих разрешениях см. в справочнике по разрешениям.
| Тип разрешения |
Разрешение с наименьшими привилегиями |
Более высокие привилегированные разрешения |
| Делегированные (рабочая или учебная учетная запись) |
User.ReadWrite.All |
Directory.ReadWrite.All |
| Делегированные (личная учетная запись Майкрософт) |
Не поддерживается. |
|
| Для приложений |
User.ReadWrite.All |
Directory.ReadWrite.All |
HTTP-запрос
POST /users
Тело запроса
В теле запроса предоставьте описание объекта user в формате JSON.
В следующей таблице перечислены свойства, необходимые при создании пользователя или агентаUser.
- Чтобы создать agentUser, необходимо указать свойство @odata.type со значением
#microsoft.graph.agentUser , в противном случае будет создан пользователь и идентификатор
- Если вы включаете свойство identities для создаваемого пользователя, не все перечисленные свойства являются обязательными. Для удостоверения социальных сетей ни одно свойство не является обязательным.
| Параметр |
Тип |
Описание |
| accountEnabled |
Логический |
Значение true, если учетная запись включена; в противном случае — значение false. |
| displayName |
String |
Имя, которое следует отобразить в адресной книге для пользователя. |
| onPremisesImmutableId |
String |
Требуется только при создании новой учетной записи пользователя, если используется федеративный домен для свойства userPrincipalName (UPN) пользователя. |
| mailNickname |
String |
Почтовый псевдоним для пользователя. |
| passwordProfile |
passwordProfile |
Пароль для профиля пользователя. Применяется только к пользователю и не разрешено для agentUser. |
| userPrincipalName |
String |
Имя субъекта-пользователя (someuser@contoso.com). Это имя пользователя для входа через Интернет в соответствии с интернет-стандартом RFC 822. В соответствии с соглашением оно должно указывать на имя пользователя для электронной почты. Общий формат: псевдоним@домен. При этом домен должен входить в коллекцию проверенных доменов клиента. Доступ к проверенным доменам клиента можно получить с помощью свойства verifiedDomains объекта organization. ПРИМЕЧАНИЕ. Это свойство не может содержать диакритические знаки. Разрешены только следующие символы: A - Z, a - z, 0 - 9, ' . - _ ! # ^ ~. Полный список разрешенных символов см. в политиках имен пользователей. |
| identityParentId |
String |
Идентификатор объекта связанного удостоверения агента. Требуется для agentUser, где @odata.type#microsoft.graph.agentUser должен быть задан и игнорироваться для обычных пользователей. Если этот параметр не задан, создается обычный пользователь. |
Так как этот ресурс поддерживает расширения, можно использовать POST операцию и добавлять пользовательские свойства с собственными данными в экземпляр пользователя при его создании.
Федеративные пользователи, созданные с помощью этого API, должны выполнять вход каждые 12 часов по умолчанию. Сведения о том, как это изменить, см. в разделе Исключения для времени существования маркера.
Примечание.
Добавление локальной учетной записи B2C к существующему объекту пользователя запрещено, если объект пользователя уже не содержит удостоверение локальной учетной записи.
Отклик
В случае успешного выполнения этот метод возвращает код отклика 201 Created и объект пользователя или агентаUser в теле отклика.
При пропуске @odata.type свойства #microsoft.graph.agentUser объекта создается объект пользователя, даже если указан идентификатор identityParentId . Попытка создать agentUser с идентификатором identityParentId , уже связанным с другим агентомUser, возвращает ошибку 400 Bad Request .
Пример
Пример 1. Создание пользователя
Запрос
В следующем примере показан запрос, указывающий только необходимые свойства.
POST https://graph.microsoft.com/beta/users
Content-type: application/json
{
"accountEnabled": true,
"displayName": "Adele Vance",
"mailNickname": "AdeleV",
"userPrincipalName": "AdeleV@contoso.com",
"passwordProfile" : {
"forceChangePasswordNextSignIn": true,
"password": "xWwvJ]6NMw+bWH-d"
}
}
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.Beta.Models;
var requestBody = new User
{
AccountEnabled = true,
DisplayName = "Adele Vance",
MailNickname = "AdeleV",
UserPrincipalName = "AdeleV@contoso.com",
PasswordProfile = new PasswordProfile
{
ForceChangePasswordNextSignIn = true,
Password = "xWwvJ]6NMw+bWH-d",
},
};
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Users.PostAsync(requestBody);
// Code snippets are only available for the latest major version. Current major version is $v0.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-beta-sdk-go"
graphmodels "github.com/microsoftgraph/msgraph-beta-sdk-go/models"
//other-imports
)
requestBody := graphmodels.NewUser()
accountEnabled := true
requestBody.SetAccountEnabled(&accountEnabled)
displayName := "Adele Vance"
requestBody.SetDisplayName(&displayName)
mailNickname := "AdeleV"
requestBody.SetMailNickname(&mailNickname)
userPrincipalName := "AdeleV@contoso.com"
requestBody.SetUserPrincipalName(&userPrincipalName)
passwordProfile := graphmodels.NewPasswordProfile()
forceChangePasswordNextSignIn := true
passwordProfile.SetForceChangePasswordNextSignIn(&forceChangePasswordNextSignIn)
password := "xWwvJ]6NMw+bWH-d"
passwordProfile.SetPassword(&password)
requestBody.SetPasswordProfile(passwordProfile)
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
users, err := graphClient.Users().Post(context.Background(), requestBody, nil)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
User user = new User();
user.setAccountEnabled(true);
user.setDisplayName("Adele Vance");
user.setMailNickname("AdeleV");
user.setUserPrincipalName("AdeleV@contoso.com");
PasswordProfile passwordProfile = new PasswordProfile();
passwordProfile.setForceChangePasswordNextSignIn(true);
passwordProfile.setPassword("xWwvJ]6NMw+bWH-d");
user.setPasswordProfile(passwordProfile);
User result = graphClient.users().post(user);
const options = {
authProvider,
};
const client = Client.init(options);
const user = {
accountEnabled: true,
displayName: 'Adele Vance',
mailNickname: 'AdeleV',
userPrincipalName: 'AdeleV@contoso.com',
passwordProfile: {
forceChangePasswordNextSignIn: true,
password: 'xWwvJ]6NMw+bWH-d'
}
};
await client.api('/users')
.version('beta')
.post(user);
<?php
use Microsoft\Graph\Beta\GraphServiceClient;
use Microsoft\Graph\Beta\Generated\Models\User;
use Microsoft\Graph\Beta\Generated\Models\PasswordProfile;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestBody = new User();
$requestBody->setAccountEnabled(true);
$requestBody->setDisplayName('Adele Vance');
$requestBody->setMailNickname('AdeleV');
$requestBody->setUserPrincipalName('AdeleV@contoso.com');
$passwordProfile = new PasswordProfile();
$passwordProfile->setForceChangePasswordNextSignIn(true);
$passwordProfile->setPassword('xWwvJ]6NMw+bWH-d');
$requestBody->setPasswordProfile($passwordProfile);
$result = $graphServiceClient->users()->post($requestBody)->wait();
Import-Module Microsoft.Graph.Beta.Users
$params = @{
accountEnabled = $true
displayName = "Adele Vance"
mailNickname = "AdeleV"
userPrincipalName = "AdeleV@contoso.com"
passwordProfile = @{
forceChangePasswordNextSignIn = $true
password = "xWwvJ]6NMw+bWH-d"
}
}
New-MgBetaUser -BodyParameter $params
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph_beta import GraphServiceClient
from msgraph_beta.generated.models.user import User
from msgraph_beta.generated.models.password_profile import PasswordProfile
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
request_body = User(
account_enabled = True,
display_name = "Adele Vance",
mail_nickname = "AdeleV",
user_principal_name = "AdeleV@contoso.com",
password_profile = PasswordProfile(
force_change_password_next_sign_in = True,
password = "xWwvJ]6NMw+bWH-d",
),
)
result = await graph_client.users.post(request_body)
Отклик
Ниже показан пример отклика.
Примечание.
Объект ответа, показанный здесь, может быть сокращен для удобочитаемости.
HTTP/1.1 201 Created
Content-type: application/json
{
"@odata.context": "https://graph.microsoft.com/beta/$metadata#users/$entity",
"id": "87d349ed-44d7-43e1-9a83-5f2406dee5bd",
"businessPhones": [],
"displayName": "Adele Vance",
"givenName": "Adele",
"jobTitle": "Product Marketing Manager",
"mail": "AdeleV@contoso.com",
"mobilePhone": "+1 425 555 0109",
"officeLocation": "18/2111",
"preferredLanguage": "en-US",
"surname": "Vance",
"userPrincipalName": "AdeleV@contoso.com"
}
Пример 2. Создание пользователя агента
Запрос
В следующем примере показан запрос, указывающий только необходимые свойства.
POST https://graph.microsoft.com/beta/users
Content-type: application/json
{
"@odata.type": "#microsoft.graph.agentUser",
"accountEnabled": true,
"displayName": "Adele Vance",
"mailNickname": "AdeleV",
"userPrincipalName": "AdeleV@contoso.com",
"identityParentId": ""
}
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.Beta.Models;
var requestBody = new AgentUser
{
OdataType = "#microsoft.graph.agentUser",
AccountEnabled = true,
DisplayName = "Adele Vance",
MailNickname = "AdeleV",
UserPrincipalName = "AdeleV@contoso.com",
IdentityParentId = "",
};
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Users.PostAsync(requestBody);
// Code snippets are only available for the latest major version. Current major version is $v0.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-beta-sdk-go"
graphmodels "github.com/microsoftgraph/msgraph-beta-sdk-go/models"
//other-imports
)
requestBody := graphmodels.NewUser()
accountEnabled := true
requestBody.SetAccountEnabled(&accountEnabled)
displayName := "Adele Vance"
requestBody.SetDisplayName(&displayName)
mailNickname := "AdeleV"
requestBody.SetMailNickname(&mailNickname)
userPrincipalName := "AdeleV@contoso.com"
requestBody.SetUserPrincipalName(&userPrincipalName)
identityParentId := ""
requestBody.SetIdentityParentId(&identityParentId)
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
users, err := graphClient.Users().Post(context.Background(), requestBody, nil)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
AgentUser user = new AgentUser();
user.setOdataType("#microsoft.graph.agentUser");
user.setAccountEnabled(true);
user.setDisplayName("Adele Vance");
user.setMailNickname("AdeleV");
user.setUserPrincipalName("AdeleV@contoso.com");
user.setIdentityParentId("");
User result = graphClient.users().post(user);
const options = {
authProvider,
};
const client = Client.init(options);
const user = {
'@odata.type': '#microsoft.graph.agentUser',
accountEnabled: true,
displayName: 'Adele Vance',
mailNickname: 'AdeleV',
userPrincipalName: 'AdeleV@contoso.com',
identityParentId: ''
};
await client.api('/users')
.version('beta')
.post(user);
<?php
use Microsoft\Graph\Beta\GraphServiceClient;
use Microsoft\Graph\Beta\Generated\Models\AgentUser;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestBody = new AgentUser();
$requestBody->setOdataType('#microsoft.graph.agentUser');
$requestBody->setAccountEnabled(true);
$requestBody->setDisplayName('Adele Vance');
$requestBody->setMailNickname('AdeleV');
$requestBody->setUserPrincipalName('AdeleV@contoso.com');
$requestBody->setIdentityParentId('');
$result = $graphServiceClient->users()->post($requestBody)->wait();
Import-Module Microsoft.Graph.Beta.Users
$params = @{
"@odata.type" = "#microsoft.graph.agentUser"
accountEnabled = $true
displayName = "Adele Vance"
mailNickname = "AdeleV"
userPrincipalName = "AdeleV@contoso.com"
identityParentId = ""
}
New-MgBetaUser -BodyParameter $params
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph_beta import GraphServiceClient
from msgraph_beta.generated.models.agent_user import AgentUser
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
request_body = AgentUser(
odata_type = "#microsoft.graph.agentUser",
account_enabled = True,
display_name = "Adele Vance",
mail_nickname = "AdeleV",
user_principal_name = "AdeleV@contoso.com",
identity_parent_id = "",
)
result = await graph_client.users.post(request_body)
Отклик
Ниже показан пример отклика.
Примечание.
Объект ответа, показанный здесь, может быть сокращен для удобочитаемости.
HTTP/1.1 201 Created
Content-type: application/json
{
"@odata.context": "https://graph.microsoft.com/beta/$metadata#users/$entity",
"@odata.type": "#microsoft.graph.agentUser",
"id": "87d349ed-44d7-43e1-9a83-5f2406dee5bd",
"businessPhones": [],
"displayName": "Adele Vance",
"givenName": "Adele",
"jobTitle": "Product Marketing Manager",
"mail": "AdeleV@contoso.com",
"mobilePhone": "+1 425 555 0109",
"officeLocation": "18/2111",
"preferredLanguage": "en-US",
"surname": "Vance",
"userPrincipalName": "AdeleV@contoso.com"
}
Пример 3. Создание пользователя с удостоверениями социальных и локальных учетных записей в Azure AD B2C
Создайте нового пользователя с удостоверением локальной учетной записи с именем для входа, адресом электронной почты для входа и удостоверением социальной сети. Этот пример обычно используется для сценариев миграции в клиентах Azure AD B2C.
Примечание.
Для удостоверений локальных учетных записей срок действия паролей должен быть отключен. Также должна быть отключена принудительная смена пароля при следующем входе.
Запрос
POST https://graph.microsoft.com/beta/users
Content-type: application/json
{
"displayName": "John Smith",
"identities": [
{
"signInType": "userName",
"issuer": "contoso.com",
"issuerAssignedId": "johnsmith"
},
{
"signInType": "emailAddress",
"issuer": "contoso.com",
"issuerAssignedId": "jsmith@yahoo.com"
},
{
"signInType": "federated",
"issuer": "facebook.com",
"issuerAssignedId": "5eecb0cd"
}
],
"passwordProfile" : {
"password": "password-value",
"forceChangePasswordNextSignIn": false
},
"passwordPolicies": "DisablePasswordExpiration"
}
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.Beta.Models;
var requestBody = new User
{
DisplayName = "John Smith",
Identities = new List<ObjectIdentity>
{
new ObjectIdentity
{
SignInType = "userName",
Issuer = "contoso.com",
IssuerAssignedId = "johnsmith",
},
new ObjectIdentity
{
SignInType = "emailAddress",
Issuer = "contoso.com",
IssuerAssignedId = "jsmith@yahoo.com",
},
new ObjectIdentity
{
SignInType = "federated",
Issuer = "facebook.com",
IssuerAssignedId = "5eecb0cd",
},
},
PasswordProfile = new PasswordProfile
{
Password = "password-value",
ForceChangePasswordNextSignIn = false,
},
PasswordPolicies = "DisablePasswordExpiration",
};
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Users.PostAsync(requestBody);
// Code snippets are only available for the latest major version. Current major version is $v0.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-beta-sdk-go"
graphmodels "github.com/microsoftgraph/msgraph-beta-sdk-go/models"
//other-imports
)
requestBody := graphmodels.NewUser()
displayName := "John Smith"
requestBody.SetDisplayName(&displayName)
objectIdentity := graphmodels.NewObjectIdentity()
signInType := "userName"
objectIdentity.SetSignInType(&signInType)
issuer := "contoso.com"
objectIdentity.SetIssuer(&issuer)
issuerAssignedId := "johnsmith"
objectIdentity.SetIssuerAssignedId(&issuerAssignedId)
objectIdentity1 := graphmodels.NewObjectIdentity()
signInType := "emailAddress"
objectIdentity1.SetSignInType(&signInType)
issuer := "contoso.com"
objectIdentity1.SetIssuer(&issuer)
issuerAssignedId := "jsmith@yahoo.com"
objectIdentity1.SetIssuerAssignedId(&issuerAssignedId)
objectIdentity2 := graphmodels.NewObjectIdentity()
signInType := "federated"
objectIdentity2.SetSignInType(&signInType)
issuer := "facebook.com"
objectIdentity2.SetIssuer(&issuer)
issuerAssignedId := "5eecb0cd"
objectIdentity2.SetIssuerAssignedId(&issuerAssignedId)
identities := []graphmodels.ObjectIdentityable {
objectIdentity,
objectIdentity1,
objectIdentity2,
}
requestBody.SetIdentities(identities)
passwordProfile := graphmodels.NewPasswordProfile()
password := "password-value"
passwordProfile.SetPassword(&password)
forceChangePasswordNextSignIn := false
passwordProfile.SetForceChangePasswordNextSignIn(&forceChangePasswordNextSignIn)
requestBody.SetPasswordProfile(passwordProfile)
passwordPolicies := "DisablePasswordExpiration"
requestBody.SetPasswordPolicies(&passwordPolicies)
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
users, err := graphClient.Users().Post(context.Background(), requestBody, nil)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
User user = new User();
user.setDisplayName("John Smith");
LinkedList<ObjectIdentity> identities = new LinkedList<ObjectIdentity>();
ObjectIdentity objectIdentity = new ObjectIdentity();
objectIdentity.setSignInType("userName");
objectIdentity.setIssuer("contoso.com");
objectIdentity.setIssuerAssignedId("johnsmith");
identities.add(objectIdentity);
ObjectIdentity objectIdentity1 = new ObjectIdentity();
objectIdentity1.setSignInType("emailAddress");
objectIdentity1.setIssuer("contoso.com");
objectIdentity1.setIssuerAssignedId("jsmith@yahoo.com");
identities.add(objectIdentity1);
ObjectIdentity objectIdentity2 = new ObjectIdentity();
objectIdentity2.setSignInType("federated");
objectIdentity2.setIssuer("facebook.com");
objectIdentity2.setIssuerAssignedId("5eecb0cd");
identities.add(objectIdentity2);
user.setIdentities(identities);
PasswordProfile passwordProfile = new PasswordProfile();
passwordProfile.setPassword("password-value");
passwordProfile.setForceChangePasswordNextSignIn(false);
user.setPasswordProfile(passwordProfile);
user.setPasswordPolicies("DisablePasswordExpiration");
User result = graphClient.users().post(user);
const options = {
authProvider,
};
const client = Client.init(options);
const user = {
displayName: 'John Smith',
identities: [
{
signInType: 'userName',
issuer: 'contoso.com',
issuerAssignedId: 'johnsmith'
},
{
signInType: 'emailAddress',
issuer: 'contoso.com',
issuerAssignedId: 'jsmith@yahoo.com'
},
{
signInType: 'federated',
issuer: 'facebook.com',
issuerAssignedId: '5eecb0cd'
}
],
passwordProfile: {
password: 'password-value',
forceChangePasswordNextSignIn: false
},
passwordPolicies: 'DisablePasswordExpiration'
};
await client.api('/users')
.version('beta')
.post(user);
<?php
use Microsoft\Graph\Beta\GraphServiceClient;
use Microsoft\Graph\Beta\Generated\Models\User;
use Microsoft\Graph\Beta\Generated\Models\ObjectIdentity;
use Microsoft\Graph\Beta\Generated\Models\PasswordProfile;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestBody = new User();
$requestBody->setDisplayName('John Smith');
$identitiesObjectIdentity1 = new ObjectIdentity();
$identitiesObjectIdentity1->setSignInType('userName');
$identitiesObjectIdentity1->setIssuer('contoso.com');
$identitiesObjectIdentity1->setIssuerAssignedId('johnsmith');
$identitiesArray []= $identitiesObjectIdentity1;
$identitiesObjectIdentity2 = new ObjectIdentity();
$identitiesObjectIdentity2->setSignInType('emailAddress');
$identitiesObjectIdentity2->setIssuer('contoso.com');
$identitiesObjectIdentity2->setIssuerAssignedId('jsmith@yahoo.com');
$identitiesArray []= $identitiesObjectIdentity2;
$identitiesObjectIdentity3 = new ObjectIdentity();
$identitiesObjectIdentity3->setSignInType('federated');
$identitiesObjectIdentity3->setIssuer('facebook.com');
$identitiesObjectIdentity3->setIssuerAssignedId('5eecb0cd');
$identitiesArray []= $identitiesObjectIdentity3;
$requestBody->setIdentities($identitiesArray);
$passwordProfile = new PasswordProfile();
$passwordProfile->setPassword('password-value');
$passwordProfile->setForceChangePasswordNextSignIn(false);
$requestBody->setPasswordProfile($passwordProfile);
$requestBody->setPasswordPolicies('DisablePasswordExpiration');
$result = $graphServiceClient->users()->post($requestBody)->wait();
Import-Module Microsoft.Graph.Beta.Users
$params = @{
displayName = "John Smith"
identities = @(
@{
signInType = "userName"
issuer = "contoso.com"
issuerAssignedId = "johnsmith"
}
@{
signInType = "emailAddress"
issuer = "contoso.com"
issuerAssignedId = "jsmith@yahoo.com"
}
@{
signInType = "federated"
issuer = "facebook.com"
issuerAssignedId = "5eecb0cd"
}
)
passwordProfile = @{
password = "password-value"
forceChangePasswordNextSignIn = $false
}
passwordPolicies = "DisablePasswordExpiration"
}
New-MgBetaUser -BodyParameter $params
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph_beta import GraphServiceClient
from msgraph_beta.generated.models.user import User
from msgraph_beta.generated.models.object_identity import ObjectIdentity
from msgraph_beta.generated.models.password_profile import PasswordProfile
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
request_body = User(
display_name = "John Smith",
identities = [
ObjectIdentity(
sign_in_type = "userName",
issuer = "contoso.com",
issuer_assigned_id = "johnsmith",
),
ObjectIdentity(
sign_in_type = "emailAddress",
issuer = "contoso.com",
issuer_assigned_id = "jsmith@yahoo.com",
),
ObjectIdentity(
sign_in_type = "federated",
issuer = "facebook.com",
issuer_assigned_id = "5eecb0cd",
),
],
password_profile = PasswordProfile(
password = "password-value",
force_change_password_next_sign_in = False,
),
password_policies = "DisablePasswordExpiration",
)
result = await graph_client.users.post(request_body)
Отклик
Ниже показан пример отклика.
Примечание. Объект отклика, показанный здесь, может быть сокращен для удобочитаемости.
HTTP/1.1 201 Created
Content-type: application/json
{
"@odata.context": "https://graph.microsoft.com/beta/$metadata#users/$entity",
"displayName": "John Smith",
"id": "4c7be08b-361f-41a8-b1ef-1712f7a3dfb2",
"identities": [
{
"signInType": "userName",
"issuer": "contoso.com",
"issuerAssignedId": "johnsmith"
},
{
"signInType": "emailAddress",
"issuer": "contoso.com",
"issuerAssignedId": "jsmith@yahoo.com"
},
{
"signInType": "federated",
"issuer": "facebook.com",
"issuerAssignedId": "5eecb0cd"
}
],
"passwordPolicies": "DisablePasswordExpiration"
}
Пример 4. Создание учетной записи клиента во внешних клиентах
В этом примере показано, как создать учетную запись клиента в Внешняя идентификация Microsoft Entra во внешних клиентах.
Примечание.
Для удостоверений локальных учетных записей срок действия пароля должен быть отключен.
Запрос
POST https://graph.microsoft.com/beta/users
Content-type: application/json
{
"displayName": "Test User",
"identities": [
{
"signInType": "emailAddress",
"issuer": "contoso.onmicrosoft.com",
"issuerAssignedId": "adelev@adatum.com"
}
],
"mail": "adelev@adatum.com",
"passwordProfile": {
"password": "passwordValue",
"forceChangePasswordNextSignIn": true
},
"passwordPolicies": "DisablePasswordExpiration"
}
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.Beta.Models;
var requestBody = new User
{
DisplayName = "Test User",
Identities = new List<ObjectIdentity>
{
new ObjectIdentity
{
SignInType = "emailAddress",
Issuer = "contoso.onmicrosoft.com",
IssuerAssignedId = "adelev@adatum.com",
},
},
Mail = "adelev@adatum.com",
PasswordProfile = new PasswordProfile
{
Password = "passwordValue",
ForceChangePasswordNextSignIn = true,
},
PasswordPolicies = "DisablePasswordExpiration",
};
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Users.PostAsync(requestBody);
// Code snippets are only available for the latest major version. Current major version is $v0.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-beta-sdk-go"
graphmodels "github.com/microsoftgraph/msgraph-beta-sdk-go/models"
//other-imports
)
requestBody := graphmodels.NewUser()
displayName := "Test User"
requestBody.SetDisplayName(&displayName)
objectIdentity := graphmodels.NewObjectIdentity()
signInType := "emailAddress"
objectIdentity.SetSignInType(&signInType)
issuer := "contoso.onmicrosoft.com"
objectIdentity.SetIssuer(&issuer)
issuerAssignedId := "adelev@adatum.com"
objectIdentity.SetIssuerAssignedId(&issuerAssignedId)
identities := []graphmodels.ObjectIdentityable {
objectIdentity,
}
requestBody.SetIdentities(identities)
mail := "adelev@adatum.com"
requestBody.SetMail(&mail)
passwordProfile := graphmodels.NewPasswordProfile()
password := "passwordValue"
passwordProfile.SetPassword(&password)
forceChangePasswordNextSignIn := true
passwordProfile.SetForceChangePasswordNextSignIn(&forceChangePasswordNextSignIn)
requestBody.SetPasswordProfile(passwordProfile)
passwordPolicies := "DisablePasswordExpiration"
requestBody.SetPasswordPolicies(&passwordPolicies)
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
users, err := graphClient.Users().Post(context.Background(), requestBody, nil)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
User user = new User();
user.setDisplayName("Test User");
LinkedList<ObjectIdentity> identities = new LinkedList<ObjectIdentity>();
ObjectIdentity objectIdentity = new ObjectIdentity();
objectIdentity.setSignInType("emailAddress");
objectIdentity.setIssuer("contoso.onmicrosoft.com");
objectIdentity.setIssuerAssignedId("adelev@adatum.com");
identities.add(objectIdentity);
user.setIdentities(identities);
user.setMail("adelev@adatum.com");
PasswordProfile passwordProfile = new PasswordProfile();
passwordProfile.setPassword("passwordValue");
passwordProfile.setForceChangePasswordNextSignIn(true);
user.setPasswordProfile(passwordProfile);
user.setPasswordPolicies("DisablePasswordExpiration");
User result = graphClient.users().post(user);
const options = {
authProvider,
};
const client = Client.init(options);
const user = {
displayName: 'Test User',
identities: [
{
signInType: 'emailAddress',
issuer: 'contoso.onmicrosoft.com',
issuerAssignedId: 'adelev@adatum.com'
}
],
mail: 'adelev@adatum.com',
passwordProfile: {
password: 'passwordValue',
forceChangePasswordNextSignIn: true
},
passwordPolicies: 'DisablePasswordExpiration'
};
await client.api('/users')
.version('beta')
.post(user);
<?php
use Microsoft\Graph\Beta\GraphServiceClient;
use Microsoft\Graph\Beta\Generated\Models\User;
use Microsoft\Graph\Beta\Generated\Models\ObjectIdentity;
use Microsoft\Graph\Beta\Generated\Models\PasswordProfile;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestBody = new User();
$requestBody->setDisplayName('Test User');
$identitiesObjectIdentity1 = new ObjectIdentity();
$identitiesObjectIdentity1->setSignInType('emailAddress');
$identitiesObjectIdentity1->setIssuer('contoso.onmicrosoft.com');
$identitiesObjectIdentity1->setIssuerAssignedId('adelev@adatum.com');
$identitiesArray []= $identitiesObjectIdentity1;
$requestBody->setIdentities($identitiesArray);
$requestBody->setMail('adelev@adatum.com');
$passwordProfile = new PasswordProfile();
$passwordProfile->setPassword('passwordValue');
$passwordProfile->setForceChangePasswordNextSignIn(true);
$requestBody->setPasswordProfile($passwordProfile);
$requestBody->setPasswordPolicies('DisablePasswordExpiration');
$result = $graphServiceClient->users()->post($requestBody)->wait();
Import-Module Microsoft.Graph.Beta.Users
$params = @{
displayName = "Test User"
identities = @(
@{
signInType = "emailAddress"
issuer = "contoso.onmicrosoft.com"
issuerAssignedId = "adelev@adatum.com"
}
)
mail = "adelev@adatum.com"
passwordProfile = @{
password = "passwordValue"
forceChangePasswordNextSignIn = $true
}
passwordPolicies = "DisablePasswordExpiration"
}
New-MgBetaUser -BodyParameter $params
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph_beta import GraphServiceClient
from msgraph_beta.generated.models.user import User
from msgraph_beta.generated.models.object_identity import ObjectIdentity
from msgraph_beta.generated.models.password_profile import PasswordProfile
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
request_body = User(
display_name = "Test User",
identities = [
ObjectIdentity(
sign_in_type = "emailAddress",
issuer = "contoso.onmicrosoft.com",
issuer_assigned_id = "adelev@adatum.com",
),
],
mail = "adelev@adatum.com",
password_profile = PasswordProfile(
password = "passwordValue",
force_change_password_next_sign_in = True,
),
password_policies = "DisablePasswordExpiration",
)
result = await graph_client.users.post(request_body)
Отклик
Ниже показан пример отклика.
Примечание. Объект отклика, показанный здесь, может быть сокращен для удобочитаемости.
HTTP/1.1 201 Created
Content-type: application/json
{
"@odata.context": "https://graph.microsoft.com/beta/$metadata#users/$entity",
"id": "daabd280-3978-4d29-acce-d677b9cf2e4d",
"businessPhones": [],
"displayName": "Test User",
"givenName": null,
"jobTitle": null,
"mail": "adelev@adatum.com",
"mobilePhone": null,
"officeLocation": null,
"preferredLanguage": null,
"surname": null,
"userPrincipalName": "daabd280-3978-4d29-acce-d677b9cf2e4d@contoso.onmicrosoft.com"
}
Связанные материалы