From 0ba2c999a6cad02e2fc40d3bdf34f56eb7e18bed Mon Sep 17 00:00:00 2001 From: Ian Allen Date: Tue, 7 Jun 2022 09:17:55 -0300 Subject: [PATCH] [BP]Update locale parsing from keycloak token to support different formats. --- ...eycloakAuthenticationProcessingFilter.java | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/core/src/main/java/org/fao/geonet/kernel/security/keycloak/KeycloakAuthenticationProcessingFilter.java b/core/src/main/java/org/fao/geonet/kernel/security/keycloak/KeycloakAuthenticationProcessingFilter.java index f6182a619ec..16d6a44a7d8 100644 --- a/core/src/main/java/org/fao/geonet/kernel/security/keycloak/KeycloakAuthenticationProcessingFilter.java +++ b/core/src/main/java/org/fao/geonet/kernel/security/keycloak/KeycloakAuthenticationProcessingFilter.java @@ -25,6 +25,7 @@ import org.apache.commons.lang.LocaleUtils; +import org.apache.commons.lang3.StringUtils; import org.fao.geonet.constants.Geonet; import org.fao.geonet.utils.Log; import org.keycloak.KeycloakPrincipal; @@ -54,9 +55,11 @@ import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLDecoder; +import java.util.IllformedLocaleException; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; +import java.util.Locale; import java.util.Map; public class KeycloakAuthenticationProcessingFilter extends org.keycloak.adapters.springsecurity.filter.KeycloakAuthenticationProcessingFilter { @@ -170,12 +173,20 @@ protected void successfulAuthentication(HttpServletRequest request, HttpServletR } // Set users preferred locale if it exists. - if (keycloakPrincipal.getKeycloakSecurityContext().getToken().getLocale() != null) { + String localeString = keycloakPrincipal.getKeycloakSecurityContext().getToken().getLocale(); + if (!StringUtils.isEmpty(localeString)) { try { - response.setLocale(LocaleUtils.toLocale(keycloakPrincipal.getKeycloakSecurityContext().getToken().getLocale())); + try { + //Try to parse the locale as a languageTag i.e. en-CA + response.setLocale(new Locale.Builder().setLanguageTag(localeString).build()); + } catch (IllformedLocaleException e) { + // If there are any exceptions try a different approach as it may be in the format of en_CA or simply en + response.setLocale(LocaleUtils.toLocale(localeString)); + } } catch (IllegalArgumentException e) { - Log.warning(Geonet.SECURITY, "Unable to parse keycloak locale " + LocaleUtils.toLocale(keycloakPrincipal.getKeycloakSecurityContext().getToken().getLocale() + - " for use " + username + ": " + e.getMessage())); + + Log.warning(Geonet.SECURITY, "Unable to parse keycloak locale " + localeString + + " for user " + username + ": " + e.getMessage()); } } }