Im setting up a Web Application using thymeleaf and spring security username and password authentication. After my login is successful im redirected to a url but Im getting a 403 on that page. Below is my configuration
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "index", "login", "/resource/**").permitAll()
.antMatchers("/userpage").hasRole("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/userpage")
.failureUrl("/login?error=true")
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/login?logout=true")
.invalidateHttpSession(true)
.permitAll()
.and()
.csrf()
.disable();
}
My User service
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.getUserByEmail(username);
if (user == null) {
throw new UsernameNotFoundException("User not found.");
}
log.info("loadUserByUsername() : {}", username);
return new org.springframework.security.core.userdetails.User(user.getId(),
user.getPassword(), getAuthority());
}
private List getAuthority() {
return Arrays.asList(new SimpleGrantedAuthority("USER")); // TODO
}
My Controllers
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login() {
return "login";
}
@RequestMapping(value = "/userpage", method = RequestMethod.GET)
public String userpage(Model model) {
model.addAttribute("user", new User());
return "user-page";
}
I can see the user being authenticated when debugging loadUserByUsername()
, but the page returns There was an unexpected error (type=Forbidden, status=403).
Once im directed with defaultSuccessUrl("/userpage")
Any help greatly appreciated
A possible issue in the above code snippet is that, you have not provided loginProcessingUrl()
. This is the place where Spring validates username and passwords
http.authorizeRequests()
.antMatchers("/", "index", "login", "/resource/**").permitAll()
.antMatchers("/userpage").hasRole("USER")
.and()
.formLogin()
.loginPage( "/myLoginPage" ) // Pointing to the controller method
.loginProcessingUrl( "/authenticateTheUser" ) // No coding is needed. Spring will automatically handle this.
.defaultSuccessUrl( "/myFirstPage", true )
.permitAll()
.and()
.logout()
.permitAll();