Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best practice to salt a password with spring security in spring boot?

I'm creating a REST API in java for an online store with Spring Boot, I want to securely store user passwords in the database, for this I am using BCrypt that comes included with spring security, I use MySQL and JPA-Hibernate for persistence.

And I am implementing it as follows:

This is the user entity:

@Entity
@SelectBeforeUpdate
@DynamicUpdate
@Table (name = "USER")
public class User {

    @Id
    @GeneratedValue
    @Column(name = "USER_ID")
    private Long userId;

    @Column(name = "ALIAS")
    private String alias;

    @Column(name = "NAME")
    private String name;

    @Column(name = "LAST_NAME")
    private String lastName;

    @Column(name = "TYPE")
    private String type;

    @Column(name = "PASSWORD")
    private String password;

    public String getPassword() {
        return password;
    }

    /**
    * When adding the password to the user class the setter asks if it is necessary or not to add the salt, 
    * if this is necessary the method uses the method BCrypt.hashpw (password, salt), 
    * if it is not necessary to add the salt the string That arrives is added intact
    */
    public void setPassword(String password, boolean salt) {
        if (salt) {
            this.password = BCrypt.hashpw(password, BCrypt.gensalt());
        } else {
            this.password = password;
        }
    }

//Setters and Getters and etc.

}

This is the repository of the user class:

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}

This is the service of the user class:

@Service
public class UserService{
    private UserRepository userRepository;
    @Autowired
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public User addEntity(User user) {
      //Here we tell the password setter to generate the salt
        user.setPassword(user.getPassword(), true);
        return userRepository.save(user);
    }

    public User updateEntity(User user) {
        User oldUser = userRepository.findOne(user.getUserId());
        /*
        *This step is necessary to maintain the same password since if we do not do this 
        *in the database a null is generated in the password field, 
        *this happens since the JSON that arrives from the client application does not 
        *contain the password field, This is because to carry out the modification of 
        *the password a different procedure has to be performed
        */
        user.setPassword(oldUser.getPassword(), false);

        return userRepository.save(user);
    }

    /**
     * By means of this method I verify if the password provided by the client application 
     * is the same as the password that is stored in the database which is already saved with the salt, 
     * returning a true or false boolean depending on the case
     */
    public boolean isPassword(Object password, Long id) {
        User user = userRepository.findOne(id);
        //To not create an entity that only has a field that says password, I perform this mapping operation
        String stringPassword = (String)((Map)password).get("password");
        //This method generates boolean
        return BCrypt.checkpw(stringPassword, user.getPassword());
    }

    /**
     *This method is used to update the password in the database
     */
    public boolean updatePassword(Object passwords, Long id) {
        User user = userRepository.findOne(id);
        //Here it receive a JSON with two parameters old password and new password, which are transformed into strings
        String oldPassword = (String)((Map)passwords).get("oldPassword");
        String newPassword = (String)((Map)passwords).get("newPassword");

        if (BCrypt.checkpw(oldPassword, user.getPassword())){
            //If the old password is the same as the one currently stored in the database then the new password is updated 
            //in the database for this a new salt is generated
            user.setPassword(newPassword, true);
            //We use the update method, passing the selected user
            updateEntity(user);
            //We return a true boolean
            return true;
        }else {
            //If the old password check fails then we return a false boolean
            return false;
        }
    }

    //CRUD basic methods omitted because it has no case for the question 
}

This is the controller that exposes the API endpoints:

@RestController
@CrossOrigin
@RequestMapping("/api/users")
public class UserController implements{
    UserService userService;
    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping( value = "", method = RequestMethod.POST )
    public User addEntity(@RequestBody User user) {
        return userService.addEntity(user);
    }

    @RequestMapping( value = "", method = RequestMethod.PUT )
    public User updateEntity(@RequestBody User user) {
        return userService.updateEntity(user);
    }

    @RequestMapping( value = "/{id}/checkPassword", method = RequestMethod.POST )
    public boolean isPassword(@PathVariable(value="id") Long id, @RequestBody Object password) {
        return userService.isPassword(password, id);
    }

    @RequestMapping( value = "/{id}/updatePassword", method = RequestMethod.POST )
    public boolean updatePassword(@PathVariable(value="id") Long id, @RequestBody Object password) {
        return userService.updatePassword(password, id);
    }
}

This is where my question comes, my method is working but I feel it is not the best way, I do not feel comfortable changing the password setter I would prefer to keep the standard form of a setter, as in the user service I think there is Opportunity to handle the user and password update differently, so try to use the @DynamicUpdate annotation in the entity but it simply does not work properly since the fields not provided in the update instead of leaving them as they were are saved Like nulls.

What I'm looking for is a better way to handle the security of passwords using Spring Boot.

like image 269
CorrOrtiz Avatar asked Mar 09 '23 03:03

CorrOrtiz


1 Answers

First of all you would like to have a unique field for each user in your online store (f.e. alias, or email), to use it as an identifier, without exposing id value to the end users. Also, as I understand, you want to use Spring Security to secure your web application. Spring security uses ROLEs to indicate user authorities (f.e. ROLE_USER, ROLE_ADMIN). So it would be nice to have a field (a list, a separate UserRole entity) to keep track of user roles.

Let's assume, that you added unique constraint to User field alias (private String alias;) and added simple private String role; field. Now you want to set up Spring Security to keep '/shop' and all sub-resources (f.e. '/shop/search') open to everyone, unsecured, resource '/discounts' available only for registered users and resource '/admin' available for administrator only.

To implement it, you need to define several classes. Let's start with implementation of UserDetailsService (needed by Spring Security to get user information):

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

private final UserRepository repository;

@Autowired
public UserDetailsServiceImpl(UserRepository repository) {
    this.repository = repository;
}

@Override
public UserDetails loadUserByUsername(String alias) {
    User user = repository.findByAlias(alias);
    if (user == null) {
        //Do something about it :) AFAIK this method must not return null in any case, so an un-/ checked exception might be a good option
        throw new RuntimeException(String.format("User, identified by '%s', not found", alias));
    }
    return new org.springframework.security.core.userdetails.User(
                           user.getAlias(), user.getPassword(),
                           AuthorityUtils.createAuthorityList(user.getRole()));
  }
}

Then, the main class for configuring Spring Security is one, that extends WebSecurityConfigurerAdapter (the example was taken from the application with a form based authentication, but you can adjust it for your needs):

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService userDetailsService;


@Override
protected void configure(HttpSecurity http) throws Exception {
    http
                .authorizeRequests()
                .antMatchers("/", "/shop/**").permitAll()
                .antMatchers("/discounts/**").hasRole("USER")
                .antMatchers("/admin/**").hasRole("ADMIN")
            .and()
                .formLogin()
                .usernameParameter("alias")
                .passwordParameter("password")
                .loginPage("/login").failureUrl("/login?error").defaultSuccessUrl("/")
                .permitAll()
            .and()
                .logout()
                .logoutUrl("/logout")
                .clearAuthentication(true)
                .invalidateHttpSession(true)
                .deleteCookies("JSESSIONID", "remember-me")
                .logoutSuccessUrl("/")
                .permitAll();
}


@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth
            .userDetailsService(userDetailsService)
            .passwordEncoder(passwordEncoder());
}

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

}

Then, in your UserService you can use something like:

...
@Autowired
private PasswordEncoder passwordEncoder;

public User addEntity(User user) {
...
    user.setPassword(passwordEncoder.encode(user.getPassword()))
...
}

All other checks (f.e. for login attempt or for accessing resource) Spring Security will do automatically, according to the configuration. There are many more things to setup and consider, but I hope I was able to explain the overall idea.

EDIT

Define bean as follows within any spring Component or Configuration

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

Then autowire it in your UserService class

@Service
public class UserService {

    private final UserRepository userRepository;

    private final PasswordEncoder passwordEncoder;

    @Autowired
    public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) {
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }

    public User addEntity(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword());
        return userRepository.save(user);
    }

   ...

    public boolean isPassword(Object password, Long id) {
        User user = userRepository.findOne(id);
        String stringPassword = (String)((Map)password).get("password");
        return passwordEncoder.matches(stringPassword, user.getPassword());
    }

    public boolean updatePassword(Object passwords, Long id) {
        User user = userRepository.findOne(id);
        String oldPassword = (String)((Map)passwords).get("oldPassword");
        String newPassword = (String)((Map)passwords).get("newPassword");

        if (!passwordEncoder.matches(oldPassword, newPassword)) {
             return false;
        }
            user.setPassword(passwordEncoder.encode(newPassword));
            updateEntity(user);
            return true;

    }

    ...
}

After that you can keep simple setter in User class.

like image 167
dmytro Avatar answered Mar 12 '23 05:03

dmytro