Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring security + LocaleResolver

i need to change locale settings after successful Authentication.

LocaleResolver:

    <bean id="localeChangeInterceptor"
    class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
    <property name="paramName" value="lng" />
    </bean>

   <bean id="localeResolver"
     class="web.MyLocaleResolver">
   </bean>

   public class MyLocaleResolver extends AbstractLocaleResolver {

   private Locale default = Locale.ENGLISH;

       @Override
       public Locale resolveLocale(HttpServletRequest hsr) {
           return this.default;
       }

       @Override
       public void setLocale(HttpServletRequest hsr, HttpServletResponse hsr1,         Locale default) {
           this.default = default;
       }

   }

Security:

     <form-login login-page="/login" 
          authentication-success-handler- ref="MySuccessAuthHandler"/>
     <beans:bean id="MySuccessAuthHandler" class="web.MySuccessfulAuthenticationHandler">
         <beans:property name="defaultTargetUrl" value="/index.htm"></beans:property>
     </beans:bean>

public class MySuccessfulAuthenticationHandler extends  SavedRequestAwareAuthenticationSuccessHandler  {
  @Override
  public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws ServletException, IOException {

        super.onAuthenticationSuccess(request, response, authentication);
        RequestContextUtils.getLocaleResolver(request).setLocale(request, response, Locale.ENGLISH);
   }

}

When i try to set locale by RequestContextUtils i get NullPointer Exception.

like image 628
elas Avatar asked Dec 09 '22 04:12

elas


1 Answers

LocaleResolver is exposed in request context by DispatcherServlet, whereas AuthenticationSuccessHandler is fired before request enters DispatcherServlet (actually, request that fired SavedRequestAwareAuthenticationSuccessHandler never enters DispatcherServlet, because this handler performs a redirect).

Thus, you cannot access LocaleResolver via RequestContextUtils in this case. You can try to inject LocaleResolver into your AuthenticationSuccessHandler explicitly, for example, with autowiring.

like image 108
axtavt Avatar answered Jan 03 '23 14:01

axtavt