Skip to content

Instantly share code, notes, and snippets.

@karbyninc
Created October 17, 2018 21:38
Show Gist options
  • Save karbyninc/a8528ce40c6015bae95460acd716a70b to your computer and use it in GitHub Desktop.
Save karbyninc/a8528ce40c6015bae95460acd716a70b to your computer and use it in GitHub Desktop.
using Sitecore.Owin.Authentication.Configuration;
using Sitecore.Owin.Authentication.Identity;
using Sitecore.Owin.Authentication.Services;
using System;
using Microsoft.AspNet.Identity.Owin;
namespace Foundation.Authentication
{
public class CreateUniqueUser : DefaultExternalUserBuilder
{
public CreateUniqueUser(string isPersistentUser) : base(bool.Parse(isPersistentUser)) { }
/// <summary>
/// Overrides the CreateUniqueUsername function to hook into how Sitecore creates users when you authenticate with Middlware.
/// </summary>
/// <param name="userManager"></param>
/// <param name="externalLoginInfo"></param>
/// <returns></returns>
protected override string CreateUniqueUserName(Microsoft.AspNet.Identity.UserManager<ApplicationUser> userManager, ExternalLoginInfo externalLoginInfo)
{
IdentityProvider identityProvider = this.FederatedAuthenticationConfiguration.GetIdentityProvider(externalLoginInfo.ExternalIdentity);
if (identityProvider == null)
throw new InvalidOperationException("Unable to retrieve identity provider for given identity");
//While you can map properties in the Sitecore.Owin.Authentication.enabler.config file, you also have the ability to analyze and assign
//user profile fields during the user's creation at this stage as well.
//This could be useful if you have certain computed properties or other factors to look at - for example taking two standardized claims (from your transformations) and then
//performing some sort of string operation on them, etc.
//Note: You can also access custom claims in here that you set programmatically in IdentityProviderProcessor.cs
var username = "";
//Iterate through our claims that were transformed, and set our sitecore username to be the value from the one entitled 'user_name'
foreach (var c in externalLoginInfo.ExternalIdentity.Claims)
{
if (c.Type.Equals("user_name"))
username = c.Value; //This is just an example to illustrate programmatically working with claims
}
string domain = identityProvider.Domain; //This comes from the <domain> tag inside of your provider configuration file - you could also just set this to whatever you want
return domain + "\\" + username;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment