2016-01-05 5 views
1

У меня есть CustomLoginSucessHandler в моем проекте MVC 4 Spring для управления действием, когда пользователь входит в систему.Метод defineTargetUrl весной Безопасность 4 не называется

Это нормально работает. В том же классе у меня есть метод determineTargetUrl, чтобы перенаправить пользователя в соответствии с его ROLE.

Вот код:

@Override 
    protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response){ 
     final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); 
     final String userName = authentication.getName();  
     log.debug("TARGET URL METHOD!"); 
     List<Authority> authorityList = authorityService.getAllAuthoritiesByUserName(userName); 

     for(Authority authority: authorityList){ 
      switch (authority.getAuthority()){ 

      case "ROLE_ADMIN": 
       return "processFile"; 

      case "ROLE_USER": 
       return "userPortal"; 

      case "ROLE_DEMO1": 
       return "processFile"; 

      case "ROLE_DEMO2": 
       return "processFile";      
      }    

     } 
     return "403"; 



    } 

Смотрите, что у меня есть log.debug("TARGET URL METHOD")

Этот журнал никогда не вызывается и, конечно, страница не перенаправляется, это будет целевой страницы по умолчанию, processFile.html.

Я озадачен, почему второй метод не вызывается, пока мой onAuthenticationSuccess работает отлично. Они находятся в одном классе.

Вот код, как создать экземпляр моей CustomLoginSucessHandler:

public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 
    @Autowired 
    private DataSource dataSource; 

    @Autowired 
    private CustomLoginSucessHandler customLoginSucessHandler; 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http.authorizeRequests().anyRequest().authenticated().and().formLogin().loginPage("/login.html") 
       .loginProcessingUrl("/login").permitAll().and().logout().logoutSuccessUrl("/") 
       .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).permitAll().and().exceptionHandling() 
       .accessDeniedPage("/403.html"); 

     http.csrf().requireCsrfProtectionMatcher(new CsrfRequestMatcher()); 
     http.formLogin().successHandler(customLoginSucessHandler); 

    } 

Спасибо.

ответ

3

Вы пытаетесь предотвратить неправильную функцию, что является основной причиной вашей проблемы. В выписке вы предоставили вам есть функция, которая , кажется, перекрывая другой:

@Override 
protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response){ 

, но на самом деле это ничего не перекрывая. Если вы проверите javadoc AuthenticationSuccessHandler, вы увидите, что он предоставляет только одну функцию: onAuthenticationSuccess, которую вы сообщили как «работающий». Он работает, но это функция overriden, и она вызвана как часть стандартной процедуры входа в систему. Если вы внимательно следить за этот пример:

CustomLoginSuccessHandler example(вероятно, вы вслед за этим уже)

вы увидите, что функция determineTargetUrl не перекрываться, но явно называется реализацией:

protected void handle(HttpServletRequest request, 
    HttpServletResponse response, Authentication authentication) throws IOException { 
    String targetUrl = determineTargetUrl(authentication); 

который, в свою очередь, обрабатывает метод, также вызывается от:

@Override 
public void onAuthenticationSuccess(HttpServletRequest request, 
    HttpServletResponse response, Authentication authentication) throws IOException { 
    handle(request, response, authentication); 
    clearAuthenticationAttributes(request); 
} 
Смежные вопросы