Skip to content

Commit

Permalink
[BP]Update locale parsing from keycloak token to support different fo…
Browse files Browse the repository at this point in the history
…rmats.
  • Loading branch information
ianwallen committed Jun 9, 2022
1 parent e5714a3 commit 0ba2c99
Showing 1 changed file with 15 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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());
}
}
}
Expand Down

0 comments on commit 0ba2c99

Please sign in to comment.