如何从Microsoft Graph API C#中的电子邮件地址获取用户ID

时间:2018-08-09 11:45:29

标签: c# microsoft-graph

我想将用户添加到组中,但是我没有用户的id,我只有电子邮件地址。

代码如下:

User userToAdd = await graphClient
    .Users["objectID"]
    .Request()
    .GetAsync();

await graphClient
    .Groups["groupObjectID"]
    .Members
    .References
    .Request()
    .AddAsync(userToAdd);

有人可以帮助我如何使用Microsoft Graph从电子邮件地址中检索ObjectId(用户ID)吗?

4 个答案:

答案 0 :(得分:3)

除上述正确答案外。

userPrincipalNameid不是外部电子邮件地址。我的情况是手动完成注册。您可以使用以下过滤器:

var user = await _graphClient.Users
    .Request()
    .Filter($"identities/any(c:c/issuerAssignedId eq '{email}' and c/issuer eq 'contoso.onmicrosoft.com')")
    .GetAsync();

src:https://docs.microsoft.com/de-de/graph/api/user-list?view=graph-rest-1.0&tabs=csharp

使用此配置来创建用户:

Microsoft.Graph.User graphUser = new Microsoft.Graph.User
{
    AccountEnabled = true,
    PasswordPolicies = "DisablePasswordExpiration,DisableStrongPassword",
    PasswordProfile = new PasswordProfile
    {
            ForceChangePasswordNextSignIn = false,
            Password = accountModel.Password,
        },
        Identities = new List<ObjectIdentity>
        {
            new ObjectIdentity()
            {
                SignInType = "emailAddress",
                Issuer ="contoso.onmicrosoft.com",
                IssuerAssignedId = email
            }
        },
};

答案 1 :(得分:1)

您可以使用id或userPrincipalName(这是一个电子邮件地址)从Graph API中检索用户的详细信息。

来自Microsoft Graph API reference

GET /users/{id | userPrincipalName}

您是否尝试将电子邮件地址用作objectID

答案 2 :(得分:0)

您可以通过几种不同的方式查找用户。

/users端点上,您可以使用其id(分配给每个帐户的GUID)或userPrincipalName(其默认域的电子邮件别名):

// Retrieve a user by id
var user  = await graphClient
    .Users["00000000-0000-0000-0000-000000000000"]
    .Request()
    .GetAsync();

// Retrieve a user by userPrincipalName
var user  = await graphClient
    .Users["user@tenant.onmicrosoft.com"]
    .Request()
    .GetAsync();

如果您使用的是Authorization Code or Implicit OAuth授权,则还可以查找通过/me端点进行身份验证的用户:

var user = await graphClient
    .Me
    .Request()
    .GetAsync();

答案 3 :(得分:0)

如果您需要检索访客用户,可以使用:

public static async Task<User> GetGuestUserByEmail(string email)
{
        try
        {
            var request = await graphClient
                .Users
                .Request()
                .Filter($"userType eq 'guest' and mail eq '{email}'") // apply filter
                .GetAsync();

            var guestUsers = request.CurrentPage.ToList();
            var user = guestUsers.FirstOrDefault();
            return user;
        }
        catch (ServiceException ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
            return null;
        }
 }