Java
javaTutorial
Implementation and security practice of Spring Boot password modification API
Implementation and security practice of Spring Boot password modification API

This article aims to guide readers to correctly implement the password modification function in Spring Boot applications, focusing on solving common logic errors, especially the pitfalls of String and Boolean type comparison, and emphasizing the importance of password hashing and salting. Ensure the security, robustness, and maintainability of password changing functionality with sample code and best practices.
introduction
Password changing functionality is a core component in any user management system. However, its implementation often involves sensitive operations and must take into account both functional correctness and security. This article will start with a common password modification implementation problem, conduct an in-depth analysis of its logical flaws, provide solutions that comply with security standards, and finally build a robust Spring Boot password modification API.
Common password changing logic traps
A common mistake when implementing password change functionality is failing to properly compare old passwords. The following logic may exist in the original code:
if (member.getPassword().equals(checkIfValidOldPassword(member, password.getOldPassword()))){
// ...
}
Here member.getPassword() returns a String password (usually a hashed password), while the checkIfValidOldPassword method (if it is designed to validate old passwords) usually returns a boolean value. Comparing String to boolean for equals is legal in Java, but almost always returns false because they are different types of objects.
Misunderstandings about Java Autoboxing
This problem does not cause an error during compilation because of the automatic boxing feature of Java. The parameter type of the equals method is Object. When a primitive type boolean is passed in as a parameter, the Java compiler will automatically box it into a Boolean object. Therefore, comparisons like String.equals(Boolean) are syntactically allowed. However, it is generally impossible for a String object and a Boolean object to be equal in content, unless the content of the String happens to be "true" or "false" and the value of the Boolean object also corresponds, which is not expected behavior.
Security Practices: Password Hashing and Salting
When handling passwords, they must never be stored in clear text or compared directly. Passwords must be hashed and salted before being stored. Spring Security provides the PasswordEncoder interface and its various implementations (such as BCryptPasswordEncoder) for securely handling passwords.
Core principles:
- Store hash values: Only the hash value of the password is stored in the database, not the clear text.
- Hashing at authentication time: The clear text password entered by the user is hashed at authentication time and then compared to the hash value stored in the database.
- Use PasswordEncoder: Use the PasswordEncoder provided by Spring Security for hashing and verification operations.
Build a secure password changing API
We will implement a secure and logically correct password changing function by refactoring ChangePasswordServiceImpl.
1. Dependency introduction and configuration
Make sure Spring Security is introduced into the project and the PasswordEncoder Bean is registered in the configuration class.
// For example, in your Spring Boot main application class or configuration class @Configuration
public class SecurityConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(); // It is recommended to use BCryptPasswordEncoder
}
}
2. ChangePasswordDto data transfer object
This DTO is used to receive password change request data sent by the client.
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
@Data
public class ChangePasswordDto {
@NotBlank(message = "Old password cannot be blank")
private String oldPassword;
@NotBlank(message = "New password cannot be blank")
@Size(min = 8, message = "The new password must be at least 8 characters long")
private String newPassword;
@NotBlank(message = "Confirm that the new password cannot be blank")
private String reNewPassword;
}
3. Member entity class
The password field in the Member entity will be used to store the hashed password.
import lombok.Getter;
import lombok.Setter;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.util.Date;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name="member",
indexes = {
@Index(
columnList = "email_address",
name = "email_address_idx",
unique = true
),
},
uniqueConstraints = {
@UniqueConstraint(
columnNames = {"email_address", "phone_number"},
name = "email_address_phone_number_uq"
)
}
)
public class Member {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// ...other fields...
@Column(name ="password", nullable = false)
private String password; // Store the hashed password}
4. ChangePasswordService business logic implementation
ChangePasswordServiceImpl will be responsible for handling the core logic of password changes, including old password verification, new password consistency checking, and hash storage of the new password.
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
@Slf4j
@Service
public class ChangePasswordServiceImpl implements ChangePasswordService {
private final MemberJpaRepository jpaRepository; // assuming you have a MemberJpaRepository
private final PasswordEncoder passwordEncoder;
@Autowired
public ChangePasswordServiceImpl(MemberJpaRepository jpaRepository, PasswordEncoder passwordEncoder) {
this.jpaRepository = jpaRepository;
this.passwordEncoder = passwordEncoder;
}
@Override
@Transactional
public Member changePassword(Long id, ChangePasswordDto passwordDto) {
// 1. Find members according to ID Optional<member> memberOptional = jpaRepository.findById(id);
if (memberOptional.isEmpty()) {
log.warn("Member with ID {} not found.", id);
// A better approach is to throw a custom exception, such as ResourceNotFoundException
throw new IllegalArgumentException("Member not found.");
}
Member member = memberOptional.get();
// 2. Verify old password // Use passwordEncoder.matches() to compare the old password entered by the user with the hashed password stored in the database if (!passwordEncoder.matches(passwordDto.getOldPassword(), member.getPassword())) {
log.warn("Invalid old password for member ID {}.", id);
// Throw a custom exception, such as InvalidOldPasswordException
throw new IllegalArgumentException("Invalid old password.");
}
// 3. Verify whether the new password and its confirmation password are consistent if (!passwordDto.getNewPassword().equals(passwordDto.getReNewPassword())) {
log.warn("New password and re-entered new password do not match for member ID {}.", id);
// Throw a custom exception, such as NewPasswordMismatchException
throw new IllegalArgumentException("New password and re-entered new password do not match.");
}
// 4. Hash the new password and update String encodedNewPassword = passwordEncoder.encode(passwordDto.getNewPassword());
member.setPassword(encodedNewPassword);
// 5. Save the updated member information return jpaRepository.save(member);
}
//The original checkIfValidOldPassword and changPassword methods are now integrated into changePassword,
// No need to exist separately as a public method to improve encapsulation and security.
}</member>
5. ChangePasswordController controller
The controller is responsible for receiving HTTP requests, calling the service layer to process business logic, and returning responses.
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(
value = "password",
produces = { MediaType.APPLICATION_JSON_VALUE }
)
public class ChangePasswordController {
private final ChangePasswordService service;
public ChangePasswordController(ChangePasswordService passwordService) {
this.service = passwordService;
}
@PostMapping("/change-password/{id}")
public ResponseEntity<member> changePassword(@Validated @RequestBody ChangePasswordDto passwordDto, @PathVariable(name = "id") Long id){
try {
Member updatedMember = service.changePassword(id, passwordDto);
return ResponseEntity.ok(updatedMember);
} catch (IllegalArgumentException e) {
// Return different HTTP status codes and error messages according to the actual situation return ResponseEntity.badRequest().body(null); // Example: return 400 Bad Request
}
}
}</member>
Notes and Summary
- Error handling: In actual applications, a more sophisticated exception handling mechanism should be used, such as custom exceptions (ResourceNotFoundException, InvalidOldPasswordException, NewPasswordMismatchException), combined with @ControllerAdvice to implement global exception handling, and return clear error information and appropriate HTTP status codes to the client.
- Password policy: Force users to set strong passwords (including uppercase and lowercase letters, numbers, special characters, and have minimum length requirements). JSR 303/380 Bean Validation annotations (such as @Pattern, @Size) can be used in ChangePasswordDto for verification.
- Security:
- Always use PasswordEncoder to hash and salt passwords.
- Avoid logging clear text passwords.
- Consider rate limiting to prevent brute force attacks.
- In a production environment, make sure to use HTTPS to encrypt passwords in transit.
- Transaction management: Service layer methods should be marked @Transactional to ensure atomicity of database operations.
By following the above guidance and best practices, you can build a Spring Boot password modification API that is both functionally correct and highly secure, effectively protecting user data.
The above is the detailed content of Implementation and security practice of Spring Boot password modification API. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20518
7
13631
4
How to configure Spark distributed computing environment in Java_Java big data processing
Mar 09, 2026 pm 08:45 PM
Spark cannot run in local mode, ClassNotFoundException: org.apache.spark.sql.SparkSession. This is the most common first step of getting stuck: even the dependencies are not correct. Only spark-core_2.12 is written in Maven, but spark-sql_2.12 is not added. SparkSession crashes as soon as it is built. The Scala version must strictly match the official Spark compiled version - Spark3.4.x uses Scala2.12 by default. If you use spark-sqljar of 2.13, the class loader cannot directly find the main class. Practical advice: Go to mvnre
How to safely map user-entered weekday string to integer value and implement date offset operation in Java
Mar 09, 2026 pm 09:43 PM
This article introduces a concise and maintainable way to map the weekday string (such as "Monday") to the corresponding serial number (1-7), and use the modulo operation to realize the forward and backward offset of any number of days (such as Monday plus 4 days to get Friday), avoiding lengthy if chains and hard-coded logic.
How to generate a list of duplicate elements using Java's Collections.nCopies_Initialization tips
Mar 06, 2026 am 06:24 AM
Collections.nCopies returns an immutable view. Calling add/remove will throw UnsupportedOperationException; it needs to be wrapped with newArrayList() to modify it, and it is disabled for mutable objects.
What is exception masking (Suppressed Exceptions) in Java_Multiple resource shutdown exception handling
Mar 10, 2026 pm 06:57 PM
What is SuppressedException: It is not "swallowed", but actively archived by the JVM. SuppressedException is not an exception loss, but the JVM quietly attaches the secondary exception to the main exception under the premise that "only one exception must be thrown" for you to verify afterwards. It is automatically triggered by the JVM in only two scenarios: one is that the resource closure in try-with-resources fails, and the other is that you manually call addSuppressed() in finally. The key difference is: the former is fully automatic and safe; the latter requires you to keep it to yourself, and it can be written as shadowing if you are not careful. try-
How to use Homebrew to install Java on Mac_A must-have Java tool chain for developers
Mar 09, 2026 pm 09:48 PM
Homebrew installs the latest stable version of openjdk (such as JDK22) by default, not the LTS version; you need to explicitly execute brewinstallopenjdk@17 or brewinstallopenjdk@21 to install the LTS version, and manually configure PATH and JAVA_HOME to be correctly recognized by the system and IDE.
How to correctly implement runtime file writing in Java applications (avoiding JAR internal write failures)
Mar 09, 2026 pm 07:57 PM
After a Java application is packaged as a JAR, data cannot be written directly to the resources in the JAR package (such as test.txt) because the JAR is essentially a read-only ZIP archive; the correct approach is to write variable data to an external path (such as a user directory, a temporary directory, or a configuration-specified path).
What is the underlying principle of array expansion in Java_Java memory dynamic adjustment analysis
Mar 09, 2026 pm 09:45 PM
ArrayList.add() triggers expansion because grow() is called when size is equal to elementData.length. The first add allocates 10 capacity, and subsequent expansion is 1.5 times and not less than the minimum requirement, relying on delayed initialization and System.arraycopy optimization.
How to safely read a line of integer input in Java and avoid Scanner blocking
Mar 06, 2026 am 06:21 AM
This article introduces typical blocking problems when using Scanner to read multiple integers in a single line. It points out that hasNextInt() will wait indefinitely when there is no subsequent input, and recommends a safe alternative with nextLine() string splitting as the core.





