11
votes

I am using spring boot with the spring-boot-starter-security dependency.

I have an application that will successfully login given the proper credentials. However, whenever I login I am not being redirected anywhere. How can I configure this?

Below is the form:

 <form th:action="@{/login}" method="post">
        <div><label> User Name : <input type="text" name="username"/> </label></div>
        <div><label> Password: <input type="password" name="password"/> </label></div>
        <div><input type="submit" value="Sign In"/></div>
 </form>

I have tried changing the th:action tag above but I wasn't able to get anywhere with it.

The MvcConfig method is below:

public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/login").setViewName("login");
    registry.addViewController("/").setViewName("login");
}
3

3 Answers

44
votes

Defining the redirection after a successful login needs to be applied on Spring Security, not Spring MVC.

The th:action defines the Spring Security endpoint that will process the authentication request. It does not define the redirection URL. Out of the box, Spring Boot Security will provide you the /login endpoint. By default, Spring Security will redirect after login to the secured ressource you tried to access. If you wish to always redirect to a specific URL, you can force that through the HttpSecurity configuration object.

Assuming you are using a recent version of Spring Boot, you should be able to use JavaConfig.

Here is a simple exemple :

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // the boolean flags force the redirection even though 
        // the user requested a specific secured resource.
        http.formLogin().defaultSuccessUrl("/success.html", true);
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService);
    }
}

Please note that you need to define a proprer endpoint to serve content for the /success.html URL. A static resource available by default in src/main/resources/public/ would do the trick for test purpose. I would personnally rather define a secured URL served by a Spring MVC Controller serving content with Thymeleaf. You don't want any anonymous user to be able to access the success page. Thymeleaf as some usefull features to interact with Spring Security while rendering the HTML content.

Regards, Daniel

2
votes

It works for me. Once the login has been successful, Spring security redirects to "/" and then, I checks if the user is authenticated and in this case, redirects it to my dashboard page.

@RequestMapping("/")
    public String index(Model model) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (!(auth instanceof AnonymousAuthenticationToken))
            return "dashboard";

        // if it is not authenticated, then go to the index...
        // other things ...
        return "index";
    }
0
votes

You can also define the post-login re-direction dynamically. It turns out to be crazy simple.

Suppose you have a controller that has complicated conditions where you need to ensure that the user is correctly logged in.

By setting a value in the "request" cache to the current request/response, and then doing a re-direct, Spring security will forward to the cached request after the login is successful.

    RequestCache requestCache = new HttpSessionRequestCache();
    requestCache.saveRequest(request,response);
    return "redirect:/login";

No, this doesn't seem to be documented anywhere. The only reference to it I found was the following:

SavedRequests and the RequestCache Interface Another responsibility of ExceptionTranslationFilter responsibilities is to save the current request before invoking the AuthenticationEntryPoint. This allows the request to be restored after the user has authenticated (see previous overview of web authentication). A typical example would be where the user logs in with a form, and is then redirected to the original URL by the default SavedRequestAwareAuthenticationSuccessHandler (see below).

The RequestCache encapsulates the functionality required for storing and retrieving HttpServletRequest instances. By default the HttpSessionRequestCache is used, which stores the request in the HttpSession. The RequestCacheFilter has the job of actually restoring the saved request from the cache when the user is redirected to the original URL.