简体   繁体   中英

Spring Security Thyemleaf page 403 after login using custom login page

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();

A 'loadUserByUsername(String username)' method is responsible for loading of credentials ( ex. from database ), not for authentication, presence of 'UserDetails' object does not mean that user with these credentials is authenticated and attached to current session.

1) Check that user's password is correct: Spring Security ( from 5) uses by default BCrypt for passwords hashing, means stored password ( in database ) should be also a hash, not plaintext.

2) There could be a conflict with Basic authentication, so try to disable it by adding:

  .and().httpBasic().disable()

to security settings chain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM