If you're using Federated Authentiation with Azure AD in combination with the Sitecore Identity Server you've more than likely encountered a weird result when you got logged in for the first time. I'm talking about the malformed, random usernames that are assigned as shown below.
Have no fear, you didn't configure anything incorrectly. That said, you do need to a bit of coding and a bit of configuration in order for the username to be something readible.
This article makes the assumption you've either followed along through or at least read the article, Configuring Federated Authentication To Azure AD With Sitecore Identity Server. We will be updating the Sitecore patch file we created there to apply our User Builder.
Configure A Custom User Builder
The simplest approach to updating the username is to update the Sitecore User Builder. The following user builder is a fairly basic approach and can be extended as desired.
The Code
public class CustomExternalUserBuilder : DefaultExternalUserBuilder { public CustomExternalUserBuilder(ApplicationUserFactory applicationUserFactory, IHashEncryption hashEncryption) : base(applicationUserFactory, hashEncryption) { }
protected override string CreateUniqueUserName(UserManager<applicationuser> userManager, ExternalLoginInfo externalLoginInfo) { if (externalLoginInfo == null) return "nullUserInfo"; if (string.IsNullOrWhiteSpace(externalLoginInfo.Email)) { var validUserName = externalLoginInfo.DefaultUserName.Replace(",", "").Replace(".", "").Replace("'", ""); return "sitecore\\" + validUserName.Replace(" ", ""); } return externalLoginInfo.Email; }
}
The Config
The patch file we created previously can now be extended within the identityProvidersPerSites
node to utilize our code above.
<identityProvidersPerSites hint="list:AddIdentityProvidersPerSites">
<mapEntry name="all sites" type="Sitecore.Owin.Authentication.Collections.IdentityProvidersPerSitesMapEntry, Sitecore.Owin.Authentication" resolve="true">
<sites hint="list">
<site>regexp:.*</site>
</sites>
<externalUserBuilder type="MyApp.UserBuilders.CustomExternalUserBuilder, MyApp" resolve="true">
<IsPersistentUser>true</IsPersistentUser>
</externalUserBuilder>
</mapEntry>
</identityProvidersPerSites>
With that in place, you'll need to delete the original user and log in again in order for a user to be created with a proper username. You can see the result below.
Depending on how you configure your user's properties as part of the Sitecore Identity Server Azure AD configuration, will depend on what is initially stored within the DefaultUserName
. As such, you may have different options available.