简体   繁体   中英

Updating User's sign in Email Address via Microsoft Graph API in C#

Using the Microsoft Graph API in C# I can successfully get a user's details and update say their first name, or details held in extension attributes. However, is it possible to update the email address that they use to sign in with?

I can see this held in the Identities section, but I can't see a way of updating the values held there.

is it possible to update the email address that they use to sign in with?

if you refer to User.identities property which:

Represents the identities that can be used to sign in to this user account.

then yes it is supported to update this property.

Note: Updating the identities property requires the User.ManageIdentities.All permission

PATCH https://graph.microsoft.com/v1.0/users/{id-or-upn}

{
    "identities": [
        {
            "signInType": "emailAddress",
            "issuer": "{tenant-name}",
            "issuerAssignedId": "{user-signIn-email}"
        }
    ]
}

C# example

var tenant = "contoso.onmicrosoft.com";
var existingEmailAddress = "current_email@contoso.com";
var newEmailAddress = "new_email@contoso.com";
        
//1 . find user
var users = await graphClient.Users
        .Request()
        .Filter($"identities/any(c:c/issuerAssignedId eq '{existingEmailAddress}' and c/issuer eq '{tenant}')")
        .Select("displayName,id,userPrincipalName")
        .GetAsync();
        
var foundUser = users.FirstOrDefault();
       
//2. update user identity
var user = new User
 {
         Identities = new List<ObjectIdentity>()
         {
             new ObjectIdentity
             {
                 SignInType = "emailAddress",
                 Issuer = tenant,
                 IssuerAssignedId = newEmailAddress    
             }
         }
 };

 await graphClient.Users[foundUser.Id].Request().UpdateAsync(user);

userPrincipalName is the field that you need to update. As per Update User Docs Using body below works for me.

PATCH https://graph.microsoft.com/v1.0/users/{USER-ID}
{
  "userPrincipalName": "alias@domain.com"
}

Add this field to the C# call and should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM