Search code examples
javaspringspring-bootspring-security

Spring Boot security, always opens login page


I am making a small app for uni. I am using Spring Boot security for my user management. The problem I have is that no matter what path I put into the browser it redirects to login.

I looked up for answers here: Spring boot security, always redirects to login page, if navigate through address bar but it did not help. I used this Spring Security - How to Fix WebSecurityConfigurerAdapter Deprecated for reference when configuring my code.

If someone can help, it would be much appreciated. Also if there is any other piece of code you may need do tell and I will edit this post.

@Data
@Configuration
@EnableWebSecurity
public class SecurityConfiguration  {

  private UserServiceImpl userService;

  @Bean
  public AuthenticationManager auth(AuthenticationConfiguration builder) throws Exception {
    return builder.getAuthenticationManager();
  }

  @Bean
  public BCryptPasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
  }

  @Bean
  public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .antMatchers(
                    "/registration**",
                    "/js/**",
                    "/css/**",
                    "/img/**").permitAll()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/login")
            .permitAll()
            .and()
        .logout()
            .invalidateHttpSession(true)
            .clearAuthentication(true)
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            .logoutSuccessUrl("/login?logout")
            .permitAll();
    return http.build();
  }
}

@Controller
@RequestMapping
public class MainController {

  @Autowired
  private UserServiceImpl userService;

  @GetMapping("/login")
  public String login() {
    return "login";
  }

  @GetMapping("/")
  public String home(Model model) {
    User currentUser = userService.getUser();
    model.addAttribute("user", currentUser);

    if (currentUser.getRoles().equals("ADMIN_ROLE"))
        return "admin-home";

    return "user-home";
  }
}

@Controller
@AllArgsConstructor
@RequestMapping("/register")
public class RegisterController {

  @Autowired
  private UserServiceImpl userService;

  @ModelAttribute("user")
  public RegisterUserAccountDTO registerUserAccountDTO(){return new RegisterUserAccountDTO();}

  @GetMapping
  public String RegistrationForm() {
    return "register";
  }

  @PostMapping
  public String registerNewUserAccount(@ModelAttribute("user") RegisterUserAccountDTO registerUserAccountDTO, BindingResult result) {
    if (result.hasErrors()) {
        return "redirect:/register?error";
    }
    List<User> allUsers = userService.getUserRepository().findAll();
    if (allUsers.isEmpty() == false) {
        for (int i = 0; i < allUsers.size(); i++) {
            if (allUsers.get(i).getEmail().equals(registerUserAccountDTO.getEmail()))
                return "redirect:/registration?usernameError";
            if (allUsers.get(i).getEmail().equals(registerUserAccountDTO.getEmail()))
                return "redirect:/registration?emailError";
        }
    }
    userService.register(registerUserAccountDTO);
    return "redirect:/register?success";
  }
}

In my application properties I have this line of code:

security.basic.enabled=false

Solution

  • Removing .anyRequest().authenticated() that dur mentioned solved it but Ralan is also correct.