Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 880
Deni Bakulić Avatar asked Mar 07 '26 04:03

Deni Bakulić


2 Answers

Spring asks you to login because you've told it that all but the excluded requests in .antMatchers("/registration**", "/js/**", "/css/**", "/img/**").permitAll() should be authenticated by .anyRequest().authenticated().

The reason your registration page does not open would be because you define registration in the permitAll but use register in the actual controller. (also i'm not sure if /registration** is valid, might have to be /registration + /registration/**)

like image 86
Ralan Avatar answered Mar 08 '26 18:03

Ralan


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

like image 44
Deni Bakulić Avatar answered Mar 08 '26 18:03

Deni Bakulić



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!