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");
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With