Saturday, November 12, 2022

Sitecore Azure AD B2C User.Identity.IsAuthenticated is false Set AuthenticationManager

 

Solution to use ExternalLoginCallBack

Sitecore exposes /identity/externallogincallback URL which basically invokes the HandleLoginLink processor whose primary responsibility is to transfer the AspNet.ExternalCookie issued by OIDC in to final AspNet.Cookies authentication token. The sitecore virtual users then get created and session is initialized. Therefore we must include the above end point as our callback end point. Once this callback is triggered, it will redirect the user to returnUrl specified.

/*
Reference
https://blog.baslijten.com/federated-authentication-in-sitecore-error-unsuccessful-login-with-external-provider/
*/
public void SignIn(string returnUrl)
{
// The param returnUrl is configured in Azure B2C Identity Provider.
// The redirect URL is to redirect to externallogincallback method of Sitecore Owin and then load returnUrl Sign-in
var properties = new AuthenticationProperties() { RedirectUri = "https://abc/identity/externallogincallback?ReturnUrl=/sign-in" };
//retain returnUrl to later redirect user to the page they first started
if(!string.IsNullOrWhiteSpace(returnUrl))
properties.Dictionary["returnUrl"] = returnUrl;
System.Web.HttpContext.Current.GetOwinContext().Authentication.Challenge(properties,
new string[] { "AzureB2C", "SignUpSignInPolicyKey" });
}

https://stackoverflow.com/questions/29907155/external-cookie-for-external-login-in-asp-net-owin

https://blog.baslijten.com/federated-authentication-in-sitecore-error-unsuccessful-login-with-external-provider

Technically this is what it does behind the scene- This is just a hack , don't use this. Refer above code snippet to redirect to Sitecore external call back to get away with External Cookie reference.
//Azure AD B2C Owin Context is null , once the token is acquired by authorization code flow
//Set Authentication Manager profile
var authenticated = HttpContext.GetOwinContext().Authentication.AuthenticateAsync("ExternalCookie");
// Send Access Token bearer to api to get logged user details
var loggedInUser = AuthenticationManager.BuildVirtualUser(string.Format(@"{0}\{1}", "external", "User-ID"), true);
loggedInUser.RuntimeSettings.AddedRoles.Add(authenticated.Result.Identity.Claims.First().Value);
loggedInUser.Profile.FullName = string.Format("{0} {1}", authenticated.Result.Identity.Name, authenticated.Result.Identity.Claims.Last().Value);
loggedInUser.Profile.Save();
AuthenticationManager.Login(loggedInUser);
userObject.IsAuthenticated = User.Identity.IsAuthenticated;