Skip to content

Instantly share code, notes, and snippets.

@Sam7
Last active March 9, 2018 04:40
Show Gist options
  • Save Sam7/10506454d6cb7f23d86672b3f4faa6a4 to your computer and use it in GitHub Desktop.
Save Sam7/10506454d6cb7f23d86672b3f4faa6a4 to your computer and use it in GitHub Desktop.
UmbracoCustomOwinStartup.OnExternalLogin.cs
private const string ClaimsTypeRole = "http://schemas.xmlsoap.org/claims/Group";
// Only take AD groups into consideration that have start with this prefix.
private const string ActiveDirectoryRolePrefix = "SG-STA-Umbraco";
// Append this prefix to the group alias in order not to get confused with manually created groups
private const string GroupAliasPrefix = "AD";
// Append this prefix to the group label / name in order not to get confused with manually created groups
private const string GroupLabelPrefix = "AD Group: ";
private static bool OnExternalLogin(BackOfficeIdentityUser autoLinkUser, ExternalLoginInfo loginInfo)
{
// Find the groups of the AD user
// (they come through as claims with the namespace 'http://schemas.xmlsoap.org/claims/Group' = ClaimsTypeRole)
var adGroupNames = loginInfo.ExternalIdentity.Claims
.Where(x => x.Type.Equals(ClaimsTypeRole, StringComparison.CurrentCultureIgnoreCase) && x.Value.StartsWith(ActiveDirectoryRolePrefix, StringComparison.CurrentCultureIgnoreCase))
// remove the prefix and add new one and clean string to Umbraco Alias standard
.ToDictionary(x => (GroupAliasPrefix + x.Value.Substring(ActiveDirectoryRolePrefix.Length)).ToCleanString(CleanStringType.Alias | CleanStringType.UmbracoCase));
// figure out what groups to add or remove.
var groupsToRemove = autoLinkUser.Groups.Where(x => x.Alias.StartsWith(GroupAliasPrefix) && !adGroupNames.ContainsKey(x.Alias)).ToArray();
var groupsToAdd = adGroupNames.Keys.Where(newGroupAlias => !autoLinkUser.Groups.Any(x => x.Alias.Equals(newGroupAlias))).ToArray();
// Remove user from groups
if (groupsToRemove.Any())
RemoveGroups(autoLinkUser, groupsToRemove);
// Remove user from groups
if (groupsToAdd.Any())
AddGroups(autoLinkUser, groupsToAdd, adGroupNames);
return adGroupNames.Any();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment