Search code examples
javaspringgrailsspring-securitylocale

Setting Grails/Spring Locale during Spring Security login - how?


In my Grails 1.3.7 application, I store the user's language and country in a domain class.

During a (Spring Security) login, I want to set the locale for the user session to the language/country stored for this user.

I'm implementing my custom listener, registered in grails-app/spring/resources.groovy:

class MyListener implements ApplicationListener<InteractiveAuthenticationSuccessEvent> {
    def config = org.codehaus.groovy.grails.commons.ConfigurationHolder.config

    void onApplicationEvent(InteractiveAuthenticationSuccessEvent event) {
            User user = User.findByUsername(event.authentication.name)
            Locale locale = new Locale(user.getLanguage(), user.getCountry())

            LocaleContextHolder.setLocale(locale)
            HttpServletRequest request = SecurityRequestHolder.request
            HttpServletResponse response = SecurityRequestHolder.response
            LocaleResolver locRes = RequestContextUtils.getLocaleResolver(request)

            locRes.setLocale(request, response, locale)
    }
}

My problem is that RequestContextUtils.getLocaleResolver returns null.

How do I set the new locale?


Solution

  • Rather than do this in the login-step, you should create a LocaleResolver implementation which can determine the correct Locale to use for a given HttpServletRequest.

    Your app will need to know how to resolve the Locale for every subsequent request that the user makes. Setting the Locale in the LocaleResolver or the LocaleContextHolder manually only affects the ThreadLocal storing the Locale for the current request. A new request will not have the same ThreadLocal and will see an unset Locale.

    It should be trivial to create an implementation which gets the currently-logged-in UserDetails from the Spring Security context and finds the Locale for the User (or you could store the details in Session, etc., the choice is up to you).