Create User in Azure AD with Microsoft Graph Client - c#

I am trying to create a User in Azure AD with Microsoft Graph Client. I am able to create the User but I couldn't find a property for the Email or Alternative Email of the User.
Here is the code:
await client.Users.Request()
.AddAsync(new User()
{
AccountEnabled = true,
DisplayName = displayName,
PasswordProfile = new PasswordProfile()
{
ForceChangePasswordNextSignIn = true,
Password = "P#ssword123"
},
UserPrincipalName = $"{displayName}#{domain}",
MailNickname = displayName,
});

The User's primary email address should also be the userPrincipalName.
That said, the properties you're looking for are mail and The property is mail and proxyAddresses (this is an array of alternative SMTP addresses). These properties, however, are read-only in Microsoft Graph at the moment.
There is an open User Voice for this: Ability to update the user's email aliases (proxyAddresses attribute). It could certainly use more votes (hint hint).
In order to populate these fields, you may need to use the Azure AD Graph API. The User object in this API includes support for writing to mail and otherMails (it also has proxyAddresses but that collection is also read-only).

Related

Microsoft.Graph - How to send from shared email box with different user names?

I am currently porting code for a service from using SMTP to Office 365.
With SMTP I am able to set different user names on a mail from shared inbox using the "from" field, while retaining the shared email box address. This does not appear to be working via Office 365.
The process flow is:
Customer fills in a web form that is sent to the shared email box
The service reads the email, allocates a user to this inquiry and sends a confirmation email back to the customer from the shared box but with the user's name
Any reply from the customer comes back to the shared box for further processing
Using the Microsoft.Graph API I can send / receive emails, but I can't spoof the user's name on to the outgoing email from the shared box, it always shows (to the recipient) as the name of the shared box.
Here is the code:
try
{
var sendMessage = new Message()
{
ToRecipients = new List<Recipient> { new Recipient()
{
EmailAddress = new EmailAddress()
{
Address = "customer#customer-domain.com"
}
}
},
From = new Recipient()
{
EmailAddress = new EmailAddress()
{
Address = "shared-box#my-domain.com",
Name = "ALLOCATED USER NAME HERE"
}
},
Subject = "Test Subject",
Body = new ItemBody()
{
ContentType = BodyType.Text,
Content = "This is a test text body"
},
Attachments = attachments
};
await Client
.Users[thisUser.Id]
.SendMail(sendMessage).Request().PostAsync();
}
catch(Exception ex)
{
Debug.WriteLine(ex);
}
Graph seems to be ignoring the recipient name altogether.
Microsoft Graph doc : Automate creating, sending and processing messages suggests
The from property can be changed if the Exchange administrator has assigned sendAs rights of the mailbox to some other users. The administrator can do this by selecting Mailbox Permissions of the mailbox owner in the Azure portal, or by using the Exchange Admin Center or a Windows PowerShell Add-ADPermission cmdlet. Then, you can programmatically set the from property to one of these users who have sendAs rights for that mailbox.
I have confirmed these permissions are set in the Office 365 portal. What else could I be missing?
Similar problem on my end, and found an answer in the microsoft docs here: It doesn't work - it always picks the profile name matching the e-mail and uses it for the friendly name.
So in your case you would have to change the from-address also, not only the from-name.

In AWS Cognito set temporary password for existing user and set status to "Enabled / FORCE_CHANGE_PASSWORD"

Is there an admin api to set a temporary password for an existing user and set the account back to "Enabled / FORCE_CHANGE_PASSWORD"?
We are in the early stages of changing authentication in an old winform app to use AWS Cognito. We are not allowed to count on users having email or sms (plant floor). We have created new users in the pool and supplied a first time temporary password. The users are in "Enabled / FORCE_CHANGE_PASSWORD" status. We tested this and the first time they log in with temp password we get the Cognito challenge and they then get the enter new password screen.
I cannot find any page or doc besides AdminCreateUser that sets password and status of account. All seem to rely on flow that involves verified email or phone.
My "google-foo" may be off so asking the question.
Here is the code in a console app we created to add the user...
var request = new AdminCreateUserRequest()
{
Username = user.COGNITO_ID,
UserPoolId = COGNITO_POOL_ID_USEAST,
TemporaryPassword = user.Password
};
var cognitoClient = new AmazonCognitoIdentityProviderClient(creds, Amazon.RegionEndpoint.USEast1);
var result = cognitoClient.AdminCreateUserAsync(request).Result;
return "User created as Enabled / FORCE_CHANGE_PASSWORD";
I could delete and re-add the user (they have no attributes) but want to avoid this.
You can use AdminUpdateUserAttributes to update the Account Status to FORCE_CHANGE_PASSWORD. If that doesn't work you can simple add a custom attribute which acts as a flag for accounts you want to disable. Then you can simply add a lambda post login which checks for this flag and forces user to change his password.

User Email Address Operations using Active Directory Graph API

I'm currently using the Microsoft.Azure.ActiveDirectory.GraphClient in a C# Cloud Service application that manages user provisioning and updates to users in Office 365 based on information stored in a database.
The issue I am facing is the setting of a user's mail address. On provisioning of a new user, setting the mail address property of the new user object causes an error to be thrown by the Graph Client. When provisioning a new user, the primary SMTP address is automatically set to the be the UPN for the user. The following code will successfully create a new user and set the primary SMTP address to be the same as the value set for the UserPrincipalName:
IUser newUser = new User();
newUser.DisplayName = "Firstname Surname";
newUser.UserPrincipalName = "someone#somewhere.com";
newUser.AccountEnabled = true;
newUser.MailNickname = "firstnamesurname";
newUser.ImmutableId = "0k3otwAAEkm8vGSKbJqRZg==";
newUser.PasswordProfile = new PasswordProfile
{
Password = "somerandompassword",
ForceChangePasswordNextLogin = true
};
newUser.UsageLocation = "GB";
_activeDirectoryClient.Users.AddUserAsync(newUser).Wait();
Fair enough - having UPN and primary email address mis-matches can cause AutoDiscover issues.
The problem I have is that the "mail" property of the user object also throws an error when set when updating a user.
The following code will successfully update a user:
User retrievedUser = new User();
List<IUser> retrievedUsers = null;
retrievedUsers = _activeDirectoryClient.Users
.Where(searchUser => searchUser.ImmutableId.Equals(0k3otwAAEkm8vGSKbJqRZg==))
.ExecuteAsync().Result.CurrentPage.ToList();
if (retrievedUsers != null && retrievedUsers.Count == 1)
{
retrievedUser = (User)retrievedUsers.First();
retrievedUser.UserPrincipalName = "someone1#somewhere.com";
retrievedUser.UpdateAsync().Wait();
}
The above code will change the user's UPN, but not update the primary SMTP address as in the add a new user scenario. This I do not understand, as it can then cause AutoDiscover issues (as the UPN is different to the primary SMTP address) and negate any reason for not being able to set the mail address when creating a new user.
I cannot find any details on how to update a user's email address, or set an additional email address as the primary SMTP address. Scenarios for this requirement are such as when a user gets married and they want to have a new email address as their primary email address.
Does anyone have any info please on how to manage a user's primary SMTP address using Microsoft.Azure.ActiveDirectory.GraphClient? I can find information on setting additional email addresses, but not on how to change the primary SMTP address.
Grateful for any help please!
From testing this myself, an update to the userPrincipalName through the AzureAD Graph API automatically updates the following properties:
mail
userPrincipalName
proxyAddresses
With the proxyAddresses property being updated to include the new userPrincipalName as the new primary SMTP address, and the old primary address is preserved but no longer the primary address. This is also reflected in Exchange Online. The proxyAddress which is prefixed with SMTP: (uppercase) is the PrimarySmtpAddress.
As an edge case, this process does not happen if the previous primary address is not the same as the previous UPN. If the UPN and PrimarySmtpAddress do not match, then when the UPN is updated through the AzureAD Graph API then the new UPN will be added as a non-primary address, and the original primary address will remain the primary address.
As far as I know, this behavior is undocumented. However, something similar is documented here: https://support.microsoft.com/en-us/help/3190357/how-the-proxyaddresses-attribute-is-populated-in-azure-ad. It seems the priority of which property determines the PrimarySmtpAddress goes mail > UPN > mailNickName.
In general, I don't think it's a good idea to directly manipulate proxyAddresses because Exchange/AD already do a lot of this for you.
Following a random thought, I've figured out how to change the primary email address for a user in the above scenario. This is done by setting the primary email address in the proxy address list for the user, denoting the primary address with the prefix of "SMTP:" (note it has to be in CAPS):
retrievedUser.ProxyAddresses = new List<string>
{
"SMTP: someone1#somewhere.com"
};
Hope this helps someone else!

Get E-mail of User Authenticated with Microsoft Account in ASP.NET Identity

I'm using the ASP.NET Identity stuff that came with the new MVC 5 templates in VS2013. I've configured external login providers so people can sign up using Google, Facebook, or Microsoft. However, I would still like to get peoples' e-mail address (e.g. for notifications, updates, etc.).
By default the app.UseGoogleAuthentication() will also request the user's e-mail address. For Facebook, I've created a new instance of the FacebookAuthenticationOptions class, and added the following scope: facebook.Scope.Add("email"). This also works.
I'm having problems getting the e-mail for people using a Microsoft Account. The MicrosoftAccountAuthenticationOptions also has a Scope property, but adding email doesn't seem to work. In the documentation I see there is a scope wl.emails but it returns an array of e-mail addresses and I'm not sure if this is the equivalent for email with Facebook.
Does anyone have a suggestion how to get the e-mail address as a claim when authenticating?
Configure the scopes for Microsoft.
var mo = new MicrosoftAccountAuthenticationOptions
{
Caption = "Live",
ClientId = clientId,
ClientSecret = clientSecret,
};
mo.Scope.Add("wl.basic");
mo.Scope.Add("wl.emails");
app.UseMicrosoftAccountAuthentication(mo);
Grab the email claim
var identity = await AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie);
var emailClaim = identity.Identity.FindFirst(ClaimTypes.Email);
Hope this helps you.
app.UseMicrosoftAccountAuthentication(new MicrosoftAccountAuthenticationOptions()
{
ClientId = "Your_client_id",
ClientSecret = "your_client_secret_key",
Scope = { "wl.basic", "wl.emails" }
});
and to get email
var externalIdentity = HttpContext.GetOwinContext().Authentication.GetExternalLoginInfoAsync();
string email=externalIdentity.Result.Email;

C# - Find all email addresses for an Active Directory user

I'm trying to get all the email addresses associated to a given AD user.
For the user I have the domain and the login name (ex. DOMAIN\UserName) and I the AD is storing the email addresses in:
The mail attribute.
In proxyAddresses attributes.
So far, I don't know what C# API to use to connect to the AD, and how to properly filter by the user to fetch all the email addresses. I'm using .NET 3.5.
Thank you.
Here's a possible solution using various classes in the System.DirectoryServices namespace.
string username = "username";
string domain = "domain";
List<string> emailAddresses = new List<string>();
PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, domain);
UserPrincipal user = UserPrincipal.FindByIdentity(domainContext, username);
// Add the "mail" entry
emailAddresses.Add(user.EmailAddress);
// Add the "proxyaddresses" entries.
PropertyCollection properties = ((DirectoryEntry)user.GetUnderlyingObject()).Properties;
foreach (object property in properties["proxyaddresses"])
{
emailAddresses.Add(property.ToString());
}
Have you looked at the DirectoryEntry class.
You can pull properties from there given you have the LDAP string set up. The propery for mail is "mail" ironic aint it ?

Categories

Resources