vdenotaris
vdenotaris

Reputation: 13637

Redirect already logged user in Spring

I'm using this Java configuration in order to manage http routes with Spring Boot + Spring Security:

@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()
        //...
}

Now, I've just one question: how can I redirect an already logged user from /login to /landing page? Have I to check this case inside the controller or in the config class as shown above?

Upvotes: 3

Views: 1821

Answers (2)

Nicolas D'Amelio
Nicolas D'Amelio

Reputation: 21

You can do this:

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

And can change this:

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

For this:

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

Upvotes: 2

Dave Syer
Dave Syer

Reputation: 58144

You could handle that in your /login" endpoint. How about something like this:

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

Or I guess you could add a filter (seems like overkill).

Upvotes: 4

Related Questions