2014-03-26 30 views
1

我爲了和春天引導+ Spring Security的管理HTTP路線正在使用此Java配置:重定向已登錄用戶在春天

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http 
     .authorizeRequests() 
      .antMatchers("/").permitAll() 
      .antMatchers("/home").permitAll()   
      .antMatchers("/public/**").permitAll() 
      .antMatchers("/signup").permitAll() 
      .anyRequest().authenticated() 
      .and() 
     .formLogin() 
      .loginPage("/login") 
      .defaultSuccessUrl("/landing") 
      .permitAll() 
     //... 
} 

現在,我只是一個問題:我怎麼能一個重定向已經登錄用戶/登錄到/登陸頁面?我是否需要在控制器內或配置類中檢查這種情況,如上所示?

+0

你能描述一下你在一個稍微詳細地想要的流量,和你看到什麼呢?它看起來像一個訪問「/登錄」的用戶將獲得一個表格,如果他成功提交,他會被轉發到「/登陸」。這不是你想要的嗎? –

+0

如果這個用戶已經登錄並繼續「/登錄」,我希望系統重定向他在「/登陸」。 – vdenotaris

回答

2

您可以處理在你的/登錄」端點如何是這樣的:。

@RequestMapping("/login") 
public String login(Principal principal) { 
    if (principal!=null && ((Authentication)principal).isAuthenticated()) { 
     return "forward:/landing"; 
    } 
    return "login"; 
} 

或者我想你可以添加過濾器(似乎有點小題大做)

1

你可以這樣做:

@RequestMapping("/login") 
public String login() { 
    Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 
    if (auth.getPrincipal() instanceof UserDetails) { 
     return "redirect:/landing"; 
    } else return "login"; 
} 

而且可以改變這一點:

http 
     .authorizeRequests() 
      .antMatchers("/").permitAll() 
      .antMatchers("/home").permitAll()   
      .antMatchers("/public/**").permitAll() 
      .antMatchers("/signup").permitAll() 

對於這個:

http 
     .authorizeRequests() 
      .antMatchers("/", "/home", "/public/**", "/signup").permitAll()