0

why i have these errors when I try to login , i want just try to log in but something went wrong , it must be redirecting to successUrl but it don't do that .

here is my security configuration

@Configuration
@EnableWebSecurity
public class SecurityConfig {


    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(authorizeRequests ->
                        authorizeRequests
                                .requestMatchers("/admin/login", "/admin/forgot-password", "/admin/reset-password").permitAll()
                                .requestMatchers("/css/**", "/js/**", "/images/**", "/fonts/**", "/vendor/**", "/img/**").permitAll()
                                .requestMatchers("/admin/**").authenticated()
                                .anyRequest().permitAll()
                )
                .formLogin(formLogin ->
                        formLogin
                                .loginPage("/admin/login")
                                .defaultSuccessUrl("/admin/students", true)
                                .permitAll()
                )
                .logout(logout ->
                        logout
                                .logoutUrl("/admin/logout")
                                .logoutSuccessUrl("/admin/login?logout")
                                .permitAll()
                )
                .csrf(AbstractHttpConfigurer::disable);

        return http.build();
    }

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

here is the controller of my login

@Controller
public class AdminLoginController {
    @Autowired
    AdminAccountService adminAccountService;

    @GetMapping("/admin/login")
    public String adminLogin(Model model) {
        model.addAttribute("title", "");
        model.addAttribute("adminLoginDTO", new AdminLoginDTO());
        return "admin-login/index";
    }

    @PostMapping(value = "/admin/login", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResponseEntity<Map<String, Object>> login(@ModelAttribute @Valid AdminLoginDTO adminLoginDTO) {
        Map<String, Object> response = new HashMap<>();
        try {
            Authentication authentication = adminAccountService.authenticate(adminLoginDTO);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            response.put("success", true);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(response);
        }
    }

the thymeleaf page

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
<h2>Login</h2>
<form th:action="@{/admin/login}" method="post" th:object="${adminLoginDTO}">
    <div>
        <label for="email">Email:</label>
        <input type="email" id="email" th:field="*{email}" required>
    </div>
    <div>
        <label for="password">Password:</label>
        <input type="password" id="password" th:field="*{password}" required>
    </div>
    <div>
        <button type="submit">Login</button>
    </div>
</form>
<div th:if="${param.error}">
    <p style="color:red;">Invalid username or password.</p>
</div>
</body>
</html>

the service of the login

@Service
public class AdminAccountServiceImpl implements AdminAccountService, UserDetailsService {
    @Autowired
    AdminAccountRepository adminAccountRepository;
    @Autowired
    private JwtAdminService jwtAdminService;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private PasswordEncoder passwordEncoder;


    @Autowired
    private AdminForgotPasswordTokenRepository adminForgotPasswordTokenRepository;

    @Autowired
    private EmailService emailService;

    @Override
    public AdminForgotPasswordToken forgotPassword(ForgotPasswordDTO forgotPasswordDTO) throws Exception {
        AdminForgotPasswordToken forgotPasswordToken = adminForgotPasswordTokenRepository.findByAdminEmail(forgotPasswordDTO.getEmail(), false).orElse(new AdminForgotPasswordToken());

        AdminAccount adminAccount = adminAccountRepository.findByEmail(forgotPasswordDTO.getEmail()).orElseThrow(() -> new Exception("Email inexistant"));

        forgotPasswordToken.setDate(LocalDate.now());
        forgotPasswordToken.setAdmin(adminAccount);
        String token = UUID.randomUUID().toString();
        forgotPasswordToken.setUserToken(token);
        forgotPasswordToken.setDone(false);

        Context contexte = new Context();
        String resetLink = "http://localhost:8080/admin/reset-password?token=" + token; 
        contexte.setVariable("resetLink", resetLink);
        contexte.setVariable("userName", adminAccount.getName());
        emailService.sendEmail(forgotPasswordDTO.getEmail(), "Réinitialisation du mot de passe de la plateforme", "codes/admin-send-code", contexte);

        adminForgotPasswordTokenRepository.save(forgotPasswordToken);

        return forgotPasswordToken;
    }

    @Override
    public AuthenticationResponse login(AdminLoginDTO adminLoginDTO) throws Exception {
        try {
            String email = adminLoginDTO.getEmail();
            String rawPassword = adminLoginDTO.getPassword();

            AdminAccount adminAccount = adminAccountRepository.findByEmail(email).orElseThrow(() -> new UserNotFoundException("L'utilisateur n'existe pas"));
            if (!passwordEncoder.matches(rawPassword, adminAccount.getPassword())) {
                throw new BadCredentialsException("Mot de passe incorrect");
            }

            return AuthenticationResponse.builder()
                    .token(jwtAdminService.generateToken(adminAccount.getEmail()))
                    .build();
        } catch (BadCredentialsException e) {
            throw new BadCredentialsException("Email ou mot de passe incorrect");
        } catch (AuthenticationException e) {
            throw new Exception("Erreur d'authentification", e);
        }
    }

    @Override
    public AdminAccount save(AdminAccount adminAccount) throws Exception {
        Optional<AdminAccount> existingAdmin = adminAccountRepository.findByEmail(adminAccount.getEmail());
        if (existingAdmin.isPresent() && !existingAdmin.get().getId().equals(adminAccount.getId())) {
            throw new Exception("Un administrateur avec cet email existe déjà");
        }
        adminAccount.setPassword(passwordEncoder.encode(adminAccount.getPassword()));
        return adminAccountRepository.save(adminAccount);
    }

    @Override
    public AdminAccount findByEmail(String email) throws UserNotFoundException {
        return adminAccountRepository.findByEmail(email).orElseThrow(() -> new UserNotFoundException("L'utilisateur n'existe pas"));
    }

    @Override
    public AdminForgotPasswordToken findByToken(String token) throws Exception {
        return adminForgotPasswordTokenRepository.findByUserToken(token).orElseThrow(() -> new Exception("Token invalide"));
    }

    @Override
    public void saveForgotPasswordToken(AdminForgotPasswordToken token) throws Exception {
        adminForgotPasswordTokenRepository.save(token);
    }

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        return adminAccountRepository.findByEmail(email)
            .orElseThrow(() -> new UsernameNotFoundException("L'utilisateur n'existe pas"));
    }

    @Override
    public Authentication authenticate(AdminLoginDTO adminLoginDTO) throws AuthenticationException {
        Authentication authentication = new UsernamePasswordAuthenticationToken(
                adminLoginDTO.getEmail(), adminLoginDTO.getPassword());
        return authenticationManager.authenticate(authentication);
    }
}

the error i've encounter

Error : failed to find 'user '

2024-08-09T14:43:26.121+03:00  INFO 2460 --- [kante] [           main] o.s.m.s.b.SimpleBrokerMessageHandler     : Started.
2024-08-09T14:43:26.127+03:00  INFO 2460 --- [kante] [           main] com.platform.app.appApplication      : Started appApplication in 7.61 seconds (process running for 8.376)
2024-08-09T14:43:32.378+03:00  INFO 2460 --- [kante] [nio-8083-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2024-08-09T14:43:32.379+03:00  INFO 2460 --- [kante] [nio-8083-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2024-08-09T14:43:32.382+03:00  INFO 2460 --- [kante] [nio-8083-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 3 ms
2024-08-09T14:43:32.414+03:00 DEBUG 2460 --- [kante] [nio-8083-exec-1] o.s.security.web.FilterChainProxy        : Securing GET /admin/login?error
2024-08-09T14:43:32.434+03:00 DEBUG 2460 --- [kante] [nio-8083-exec-1] o.s.security.web.FilterChainProxy        : Secured GET /admin/login?error
2024-08-09T14:43:33.122+03:00 DEBUG 2460 --- [kante] [nio-8083-exec-1] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
2024-08-09T14:43:36.892+03:00 DEBUG 2460 --- [kante] [nio-8083-exec-2] o.s.security.web.FilterChainProxy        : Securing GET /admin/login
2024-08-09T14:43:36.892+03:00 DEBUG 2460 --- [kante] [nio-8083-exec-2] o.s.security.web.FilterChainProxy        : Secured GET /admin/login
2024-08-09T14:43:36.901+03:00 DEBUG 2460 --- [kante] [nio-8083-exec-2] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
2024-08-09T14:43:38.341+03:00 DEBUG 2460 --- [kante] [nio-8083-exec-3] o.s.security.web.FilterChainProxy        : Securing GET /admin/login?error
2024-08-09T14:43:38.341+03:00 DEBUG 2460 --- [kante] [nio-8083-exec-3] o.s.security.web.FilterChainProxy        : Secured GET /admin/login?error
2024-08-09T14:43:38.349+03:00 DEBUG 2460 --- [kante] [nio-8083-exec-3] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
2024-08-09T14:43:41.261+03:00 DEBUG 2460 --- [kante] [nio-8083-exec-4] o.s.security.web.FilterChainProxy        : Securing GET /admin/login

2024-08-09T14:43:41.261+03:00 DEBUG 2460 --- [kante] [nio-8083-exec-4] o.s.security.web.FilterChainProxy        : Secured GET /admin/login
2024-08-09T14:43:41.269+03:00 DEBUG 2460 --- [kante] [nio-8083-exec-4] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
2024-08-09T14:43:44.207+03:00 DEBUG 2460 --- [kante] [nio-8083-exec-5] o.s.security.web.FilterChainProxy        : Securing POST /admin/login
2024-08-09T14:43:44.481+03:00 DEBUG 2460 --- [kante] [nio-8083-exec-5] o.s.s.a.dao.DaoAuthenticationProvider    : Failed to find user ''
2024-08-09T14:43:44.490+03:00 DEBUG 2460 --- [kante] [nio-8083-exec-5] o.s.s.web.DefaultRedirectStrategy        : Redirecting to /admin/login?error
2024-08-09T14:43:44.495+03:00 DEBUG 2460 --- [kante] [nio-8083-exec-6] o.s.security.web.FilterChainProxy        : Securing GET /admin/login?error
2024-08-09T14:43:44.495+03:00 DEBUG 2460 --- [kante] [nio-8083-exec-6] o.s.security.web.FilterChainProxy        : Secured GET /admin/login?error
2024-08-09T14:43:44.499+03:00 DEBUG 2460 --- [kante] [nio-8083-exec-6] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
2024-08-09T14:43:52.469+03:00 DEBUG 2460 --- [kante] [nio-8083-exec-7] o.s.security.web.FilterChainProxy        : Securing POST /admin/login
2024-08-09T14:43:52.622+03:00 DEBUG 2460 --- [kante] [nio-8083-exec-7] o.s.s.a.dao.DaoAuthenticationProvider    : Failed to find user ''
2024-08-09T14:43:52.623+03:00 DEBUG 2460 --- [kante] [nio-8083-exec-7] o.s.s.web.DefaultRedirectStrategy        : Redirecting to /admin/login?error
2024-08-09T14:43:52.629+03:00 DEBUG 2460 --- [kante] [nio-8083-exec-8] o.s.security.web.FilterChainProxy        : Securing GET /admin/login?error
2024-08-09T14:43:52.629+03:00 DEBUG 2460 --- [kante] [nio-8083-exec-8] o.s.security.web.FilterChainProxy        : Secured GET /admin/login?error
2024-08-09T14:43:52.632+03:00 DEBUG 2460 --- [kante] [nio-8083-exec-8] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
2024-08-09T14:43:53.800+03:00 DEBUG 2460 --- [kante] [nio-8083-exec-9] o.s.security.web.FilterChainProxy        : Securing POST /admin/login
2024-08-09T14:43:53.969+03:00 DEBUG 2460 --- [kante] [nio-8083-exec-9] o.s.s.a.dao.DaoAuthenticationProvider    : Failed to find user ''
2024-08-09T14:43:53.969+03:00 DEBUG 2460 --- [kante] [nio-8083-exec-9] o.s.s.web.DefaultRedirectStrategy        : Redirecting to /admin/login?error
2024-08-09T14:43:53.975+03:00 DEBUG 2460 --- [kante] [io-8083-exec-10] o.s.security.web.FilterChainProxy        : Securing GET /admin/login?error
2024-08-09T14:43:53.976+03:00 DEBUG 2460 --- [kante] [io-8083-exec-10] o.s.security.web.FilterChainProxy        : Secured GET /admin/login?error
2024-08-09T14:43:53.982+03:00 DEBUG 2460 --- [kante] [io-8083-exec-10] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
2024-08-09T14:44:26.104+03:00  INFO 2460 --- [kante] [MessageBroker-1] o.s.w.s.c.WebSocketMessageBrokerStats    : WebSocketSession[0 current WS(0)-HttpStream(0)-HttpPoll(0), 0 total, 0 closed abnormally (0 connect failure, 0 send limit, 0 transport error)], stompSubProtocol[processed CONNECT(0)-CONNECTED(0)-DISCONNECT(0)], stompBrokerRelay[null], inboundChannel[pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0], outboundChannel[pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0], sockJsScheduler[pool size = 1, active threads = 1, queued tasks = 0, completed tasks = 0]

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.