Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get user id from email address in Microsoft Graph API C#

I want to add User to a Group but I don't have the User's id, I only have the email address.

Here is the code:

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

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

Can someone help how do I retrieve ObjectId (User ID) from an email address using Microsoft Graph?

like image 539
sidi shah Avatar asked Aug 09 '18 11:08

sidi shah


1 Answers

Besides these correct answers above.

userPrincipalName or id is not the external email address. That was my case when registration is done manually. You can use this filter:

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/en-us/graph/api/user-list?view=graph-rest-1.0&tabs=csharp

Using this configuration to create an user:

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
            }
        },
};
like image 141
boehlefeld Avatar answered Oct 18 '22 13:10

boehlefeld