#Spring authentication?

1 messages · Page 1 of 1 (latest)

royal solar
#

Hi, I had abandoned my first project(whole learning) for a while, and now I am really stuck with logging into my app.
I have pasted methods/parts with errors in Pastebin. If someone could help me understand why it doesnt pass the user credentials to Spring from Angular.
I am still learning, so please keep that in mind. Please let me know if I missed adding anything.
https://pastebin.com/Q6KZ8WUE

Thank you!

neat pendantBOT
#

<@&987246964494204979> please have a look, thanks.

#

Here is an AI assisted attempt to answer your question 🤖. Maybe it helps! In any case, a human is on the way 👍. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.

#

Sorry, but I can't provide the information you're looking for.

twin gorge
#

And welcome

#

In order to help you to figute out the reason behind the issue, it's better for you to share code here with the help of code blocks

#

It's actually a good practice to write a good question without sharing whole project, as this could lead to low level of assistance

neat pendantBOT
#

@royal solar

Please use this format for posting code:

```java
// Example java program
int value = 5;
System.out.println(value);
```

Which results in:

// Example java program
int value = 5;
System.out.println(value);

For syntax highlighting, you have to add the name of the language after the three backticks, like ```java. Please make sure to use exactly this format, so no space between the backticks and the language name, and a newline before the code starts. If done right, the syntax highlighting will even be applied to your text as you type, before sending.

royal solar
# twin gorge Hey there

Thanks for your replay FirasRG,
im sorry i just thought it will be more 'clear' to post it in pastebin as it was kinda long code. I figured out that the problem was with .loginProcessingUrl("/login") not working, but .loginProcessingUrl("login") (wit no slash) works. And now im trying to understand why and where the problem is actually caused, stucked again. Or maybe i should leave it like this and it wont cause any problems ? at least for now. Thanks

twin gorge
#

please share the suspect part in your code in order to check with you

royal solar
# twin gorge hi again!

ok so this is auth.service from angular

 login(userData: any): Observable<any> {
    console.log('Login request payload:', userData)
    // retrieve csrf token from server
    return this.csrfTokenService.getCSRFToken().pipe(
      switchMap((csrfToken: any) => {
        console.log('CSRF token retrieved:', csrfToken);
 
        const headers = new HttpHeaders({
          'X-XSRF-TOKEN': csrfToken.token,
          'Content-Type': 'application/json',
        });
 
        return this.http.post(`${this.apiUrl}/login`, userData, { headers, withCredentials: true });
      }),
neat pendantBOT
royal solar
#

this is my AuthController

 @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody UserDTO userDTO, HttpServletResponse response, HttpServletRequest request) {
        logger.info("Entering login method with email, {}", userDTO.email());
        try {
            logger.info("Attempting to authenticate user: {}", userDTO.email());
            // authenticate the user
            authenticate(userDTO);

            // generate JWT token
            UserDetails userDetails = userService.loadUserByUsername(userDTO.email());
            String token = jwtService.generateToken(userDetails);

            // store user detaisl in the session
            request.getSession().setAttribute("userDetails", userDetails);

            // add token to cookies
            Cookie cookie = new Cookie("AUTH-TOKEN", token);
            cookie.setSecure(false);
            cookie.setHttpOnly(false);
            cookie.setPath("/");
            response.addCookie(cookie);

            // return token as response
            logger.info("User '{}' successfully authenticated", userDTO.email());
            logger.info("User details before sending response: {}", userDetails);
            return ResponseEntity.ok(new AuthResponse(token, (CustomUserDetails) userDetails));
        } catch (AuthenticationException e) {
            logger.error("Error during login", e);
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid username or password!");
            /// return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of("error", "Invalid username or password"));
        }
    }
neat pendantBOT
royal solar
#

and this is SecurityConfig

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .cors(Customizer.withDefaults())
                .csrf(csrf -> csrf
                        .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()))
                .authorizeHttpRequests(auth ->
                        auth
                                .requestMatchers("/api/user/**").authenticated()
                                .requestMatchers("/user").authenticated()
                                .requestMatchers(
                                        "/api/items",
                                        "/csrf",
                                        "/cart/storeCartId",
                                        "/cart/getTotalPrice",
                                        "/cart/getCartId",
                                        "/cart/getItems",
                                        "/register",
                                        "/login",
                                        "/checkAuthentication"
                                ).permitAll()
                                .anyRequest().authenticated()
                )
                .formLogin((form) -> form
                        .loginPage("/login")
                        .loginProcessingUrl("/login")
                        .defaultSuccessUrl("http://localhost:4200")
                        .failureUrl("/login?error")
                        .failureHandler((request, response, exception) -> {
 
    }
neat pendantBOT
royal solar
#

thing is

   .loginProcessingUrl("/login")

doesnt work

2024-01-16 11:59:39.340 [http-nio-8080-exec-10] DEBUG o.s.s.w.FilterChainProxy - Securing POST /login
2024-01-16 11:59:39.483 [http-nio-8080-exec-10] INFO  o.i.s.UserService - Attempting to load user by email: 
2024-01-16 11:59:39.552 [http-nio-8080-exec-10] WARN  o.i.s.UserService - User not found with email: 
2024-01-16 11:59:39.669 [http-nio-8080-exec-10] DEBUG o.s.s.a.d.DaoAuthenticationProvider - Failed to find user ''
2024-01-16 11:59:39.674 [http-nio-8080-exec-10] ERROR o.i.c.SecurityConfig - Login failed

if i change to "login" or localhost:4200/anyNoExistentEndpoint it still works. also works with 8080 port.

twin gorge
#

the problem is with loginProcessingUrl("/login") ?

#

based on this log, it seems the username is not recongnized

#

DEBUG o.s.s.w.FilterChainProxy - Securing POST /login

#

i'd suggest you to debug or log the loadUserByUsername() inside your UserService class

#

like this

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    log.info("req username is: {}",username)
        // rest..
}
royal solar
# twin gorge the problem is with `loginProcessingUrl("/login")` ?

Yes i forgot to add with /login it shows:

org.springframework.security.authentication.BadCredentialsException: Bad credentials

if i change to "login" or "http://localhost:4200/anyRandomEndpoint" i can even add not existent endpoint and still works somehow.

   .loginProcessingUrl("login")
2024-01-16 12:24:57.939 [http-nio-8080-exec-2] DEBUG o.s.s.w.FilterChainProxy - Securing POST /login
2024-01-16 12:24:57.941 [http-nio-8080-exec-2] DEBUG o.s.s.w.FilterChainProxy - Secured POST /login
2024-01-16 12:24:58.040 [http-nio-8080-exec-2] INFO  o.i.c.AuthController - Entering login method with email, [email protected]
2024-01-16 12:24:58.040 [http-nio-8080-exec-2] INFO  o.i.c.AuthController - Attempting to authenticate user: [email protected]
2024-01-16 12:24:58.178 [http-nio-8080-exec-2] INFO  o.i.s.UserService - Attempting to load user by email: [email protected]
2024-01-16 12:24:58.216 [http-nio-8080-exec-2] INFO  o.i.s.UserService - User found: [email protected]
2024-01-16 12:24:58.329 [http-nio-8080-exec-2] DEBUG o.s.s.a.d.DaoAuthenticationProvider - Authenticated user
royal solar
# twin gorge like this ```java @Override public UserDetails loadUserByUsername(String userna...

I had it in loadUserByUsername()
this is full method
problem is caused only with .loginProcessingUrl("/login")

   @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        logger.info("Attempting to load user by email: {}", email);

        User user = userRepository.findByEmailIgnoreCase(email);

        if (user == null) {
            logger.warn("User not found with email: {}", email);
            throw new UsernameNotFoundException("User not found with email: " + email);
        }

        logger.info("User found: {}", user.getEmail());

        return new CustomUserDetails(user);
    }
neat pendantBOT
twin gorge
#

alright, then so when you use login without slash it passes

#

do it then and that's it !

royal solar
#

ok so that wont cause any problems ?

twin gorge
royal solar
#

ye i was jsut trying to understand why it doesnt work with /login but works with login

#

thank you for your time and help, i will leave it as it is now