Sitecore Custom API Issue with Federation Authentication
In earlier segments, detailed in Part 1 and Part 2 of the blogs on Keycloak Integration with Sitecore, I introduced Keycloak functionality for CM login. Concurrently, I addressed a necessity to develop custom APIs for retrieving Sitecore users and roles.
Following the development of custom APIs, during authentication failures, the API erroneously returned a status code of 200 instead of 401.
The problem arose because API requests were being routed through the "owin.identityProviders" pipeline, which was not intended for API usage.
Solution:
When OWIN identifies a 401 response and the AuthenticationMode is set to "Active," it fails to capture the URL hash included in the request.
Another choice is to activate the "Passive" AuthenticationMode, wherein OWIN refrains from actively intercepting 401 responses. In passive mode, your application needs to explicitly issue a Challenge to trigger the OWIN authorization process.
To resolve this problem, I implemented a Passive mode like so: 'AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Passive', which successfully resolved the issue.
public class KeycloakIdentityProvider : IdentityProvidersProcessor
{
protected override string IdentityProviderName => "keycloak";
private string ClientId => Settings.GetSetting(KeycloakSettings.ClientId, "");
private string ClientSecret => Settings.GetSetting(KeycloakSettings.ClientSecret, "");
private string Authority => Settings.GetSetting(KeycloakSettings.Authority, "");
private string MetadataAddress => Settings.GetSetting(KeycloakSettings.MetadataAddress, "");
private string RedirectURL => Settings.GetSetting(KeycloakSettings.RedirectURL, "");
private readonly string OpenIdScope = OpenIdConnectScope.OpenIdProfile + " email";
private readonly string idToken = "id_token";
private readonly string accessDeniedRelativePath = "/custom/errorpages/Forbidden.aspx";
public KeycloakIdentityProvider(FederatedAuthenticationConfiguration federatedAuthenticationConfiguration, Microsoft.Owin.Infrastructure.ICookieManager cookieManager, BaseSettings settings) : base(federatedAuthenticationConfiguration, cookieManager, settings)
{
}
protected IdentityProvider IdentityProvider { get; set; }
protected override void ProcessCore(IdentityProvidersArgs args)
{
IdentityProvider = this.GetIdentityProvider();
var httphandler = new HttpClientHandler();
httphandler.DefaultProxyCredentials = CredentialCache.DefaultCredentials;
httphandler.CheckCertificateRevocationList = true;
httphandler.ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) =>
{
return true;
};
var options = new OpenIdConnectAuthenticationOptions
{
AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Passive,
BackchannelHttpHandler = httphandler,
//Backchannel = httpclient,
RequireHttpsMetadata = false,
MetadataAddress = MetadataAddress,
ClientId = ClientId,
ClientSecret = ClientSecret,
Authority = Authority,
RedirectUri = RedirectURL,
ResponseType = OpenIdConnectResponseType.Code,
Scope = OpenIdScope,
AuthenticationType = IdentityProvider.Name,
RedeemCode = true,
TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name"
},
Notifications = new OpenIdConnectAuthenticationNotifications
{
RedirectToIdentityProvider = notification =>
{
if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication)
{
if (Sitecore.Context.User.IsAuthenticated)
{
notification.HandleResponse();
notification.Response.Redirect(Settings.GetSetting("Identity.sso.launchpad"));
}
else
{
notification.ProtocolMessage.SetParameter("kc_idp_hint", "saml");
}
}
if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.Logout)
{
// If signing out, add the id_token_hint
var idTokenClaim = notification.OwinContext.Authentication.User.FindFirst(idToken);
if (idTokenClaim != null)
notification.ProtocolMessage.IdTokenHint = idTokenClaim.Value;
}
return System.Threading.Tasks.Task.CompletedTask;
}
}
};
args.App.UseKentorOwinCookieSaver();
args.App.UseOpenIdConnectAuthentication(options);
}
}
Comments