#Cors() is deprecated (Spring Security)

1 messages · Page 1 of 1 (latest)

forest moth
#

Hello. This is my first time creating a Spring Boot application in Java. I have been following along a YouTube video tutorial on how to create a registration system with user verification email. I'm now at the point of implementing Spring Security Filter Chain. However, according to the IDE, many of the methods (like cors) are now deprecated. Can someone help me update the implementation?

The user account has no types (ADMIN, USER).

package com.myname.wetalk.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class UserRegistrationSecurityConfig {
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    public SecurityFilterChain securityFilterChain(HttpSecurity http) {
        return http.cors().and().csrf().disable()
                .authorizeHttpRequests().requestMatchers()
                .permitAll().and().authorizeHttpRequests()
                .requestMatchers("")
                .and().formLogin().and().build();
    }
}
shy summitBOT
#

This post has been reserved for your question.

Hey @forest moth! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

placid flame
#

This type of configuration switched to an approach using lambdas

placid flame
#

try something like

http
    .cors(Customizer.withDefaults())
    .csrf(c->c.disable())
    .authorizeHttpRequests(c->c
        .requestMatchers("")
    )
    .formLogin(Customizer.withDefaults())
    .build();
forest moth
#

Thank you that worked. but now when I try to log in, it throws a "Bad credentials" error even though I got the credentials correct. Could it be because of the encryption implementation?

shy summitBOT
forest moth
#
package com.myname.wetalk.user;

import com.myname.wetalk.registration.RegistrationRequest;

import java.util.List;
import java.util.Optional;

public interface IUserService {
    List<User> getUsers();
    User registerUser(RegistrationRequest request);
    Optional<User> findByEmail(String email);
    Optional<User> findByUsername(String username);

    void saveUserVerificationToken(User newUser, String verificationToken);
}
package com.myname.wetalk.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class UserRegistrationSecurityConfig {
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http
                .cors(Customizer.withDefaults())
                .csrf(c->c.disable())
                .authorizeHttpRequests(c->c
                        .requestMatchers("/register").permitAll())
                .authorizeHttpRequests(c->c
                        .requestMatchers("/users").authenticated())
                .formLogin(Customizer.withDefaults())
                .build();
    }
}
#
package com.myname.wetalk.user;

// imports

@Service
@RequiredArgsConstructor
public class UserService implements IUserService {
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    private final VerificationTokenRepository tokenRepository;
    @Override
    public List<User> getUsers() {
        return userRepository.findAll();
    }

    @Override
    public User registerUser(RegistrationRequest request) {
        Optional<User> userEmail = this.findByEmail(request.email());
        Optional<User> userUsername = this.findByUsername(request.username());
        if (userUsername.isPresent()) {
            throw new UserAlreadyExistsException("The username" + request.username() + " is already taken.");
        }
        if (userEmail.isPresent()) {
            throw new UserAlreadyExistsException("The email" + request.email() + " is already in use.");
        }
        var newUser = new User();
        newUser.setFirstName(request.firstName());
        newUser.setLastName(request.lastName());
        newUser.setUsername(request.username());
        newUser.setEmail(request.email());
        newUser.setPassword(passwordEncoder.encode(request.password())); // Bcrypt encoder
        return userRepository.save(newUser);
    }

    @Override
    public Optional<User> findByEmail(String email) {
        return userRepository.findByEmail(email);
    }

    @Override
    public Optional<User> findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    @Override
    public void saveUserVerificationToken(User newUser, String token) {
        var verificationToken = new VerificationToken(token, newUser);
        tokenRepository.save(verificationToken);
    }
}
placid flame
#

You don't tell Spring about your user information

#

I think it should write a pasword to the console

#

and the username should be user

forest moth
#

this is what it outputs upon logging in

Hibernate: select u1_0.username,u1_0.email,u1_0.first_name,u1_0.is_active,u1_0.last_name,u1_0.password,u1_0.profile_picture from users u1_0 where u1_0.username=?

forest moth
placid flame
#

Do you have a UserDetailService or AuthenticationManager?

forest moth
#
package com.myname.wetalk.security;

import com.myname.wetalk.user.User;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;

@Data
public class UserRegistrationDetails implements UserDetails {

    private String username;
    private String password;
    private boolean isActive;
    private List<GrantedAuthority> authorities;

    public UserRegistrationDetails(User user) {
        this.username = user.getUsername();
        this.password = user.getPassword();
        this.isActive = user.isActive();
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return isActive();
    }
}
#

this?

#

or maybe this

package com.myname.wetalk.security;

// imports

@Service
@RequiredArgsConstructor
public class UserRegistrationDetailsService implements UserDetailsService {
    private final UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return userRepository.findByUsername(username)
                .map(UserRegistrationDetails::new)
                .orElseThrow(()-> new UsernameNotFoundException("Username is not registered."));
    }
}
placid flame
#

Does that return the thing you expect it to return?

forest moth
#

I tried inserting an output line

  @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println(username);
        return userRepository.findByUsername(username)
                .map(UserRegistrationDetails::new)
                .orElseThrow(()-> new UsernameNotFoundException("Username is not registered."));```
#

it output the correct username. but when i tried a username that is not registered, it doesnt throw the UsernameNotFoundException exception

placid flame
#

oh wait so it does let you log in when the username/password are correct?

forest moth
#

i tried gibberish input

#

when I log in using the correct credentials, Im expecting an "Account not enabled" or sth error

#

but thats from youtube

placid flame
forest moth
#

correct credentials

#

because the account hasnt been verified yet

forest moth
placid flame
placid flame
#

Can you try enabling verbose logging for Spring security?

forest moth
#

the isEnabled, however, is implemented. It returns isActive because the name is different (in the db and user model its called isActive)

#

it will get activated once the user receives the confirmation email and activates it through the link provided

forest moth
forest moth
#

im actually kinda confused because there's no /login yet in my program

#

i was just following the video i was watching. he tested his and it was fine

#
  logging:
    level:
      org:
        springframework:
          security: DEBUG```
forest moth
placid flame
forest moth
#

i see

placid flame
#

that's what the formlogin() does

#

amongst other things

placid flame
#

just post it here

forest moth
placid flame
forest moth
#

yes

placid flame
#

ah I see it

forest moth
#

idk what i did wrong i only followed along the video lmao

placid flame
#

Can you change the logging to VERBOSE instead of DEBUG?

#

or TRACE

#

I think the issue may be it having some issues with the hashed password

#

maybe it expects a delegating PasswordEncoder

forest moth
#

okay hold on

placid flame
#

idk whether that actually does anything

forest moth
#

it now worked

#

i dont know how

#

what i did was i registered another user

#

i removed the old one

#

lemme try a different user

placid flame
forest moth
#

hmm now it says its disabled even when the password is incorrect

#

no i double checked it

#

the password was 123456

#

now i changed it to password

#

could it be because they were all numbers?

#

but i doubt it

forest moth
#

when it was deactivated, it would still say its disabled even when the password was incorrect

#

when i enabled the account, doing the same thing gives me bad credentials error as expected

forest moth
#

ill make another account with the same 123456 password

#

yeah it works

#

thank you for your help and time

shy summitBOT
# forest moth thank you for your help and time

If you are finished with your post, please close it.
If you are not, please ignore this message.
Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.

forest moth
#

and patience with me

#

(ill close the post in a moment)

placid flame
shy summitBOT
placid flame
forest moth
#

because it has to be false by default

#

maybe the video hasnt gotten into that issue yet

placid flame
forest moth
#

i tried 123456 it works now too

#

maybe something went wrong when i registered the first time

placid flame
#

which saved a wrong password hash

forest moth
#

hmm perhaps

#

thank you again

shy summitBOT
# forest moth thank you again

If you are finished with your post, please close it.
If you are not, please ignore this message.
Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.