Home > Enterprise >  Spring Boot security, always opens login page
Spring Boot security, always opens login page

Time:08-15

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

CodePudding user response:

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/**)

CodePudding user response:

You are doing wrong. You need to

  1. check session is exists or not.
  2. you can get current user from session not from database. pass parameter Authentication.

EX:

@GetMapping(value = "/")
    public String defaultHome(final Model model, Authentication auth) {
        if (auth != null && auth.getName() != null) {
//Session created by springsecurity
            model.addAttribute("user", auth.getName());
        }else{
// no session found
}
...
  • Related