Spring Security中更新Principal用户姓名及排查更新后查询异常
Let’s break down how to resolve both your issues: updating the user’s name in the Principal for the welcome message, and fixing the "No user found" error when calling getUserObject().
1. Updating the Principal After AJAX PUT Request
When you update the user’s first/last name via your AJAX endpoint, you need to refresh the GreenBusUser object stored in the SecurityContextHolder—this ensures the welcome message across all pages picks up the new name immediately. Here’s how to implement this:
Step 1: Parse the JSON Request & Update the User
First, extract the new name values from the incoming JSON request body. Assuming you’re using Spring (given your mention of SecurityContextHolder and ModelMap), use @RequestBody to bind the JSON to your GreenBusUser class, then update and persist the user:
@PutMapping("/restify/updateUserData") public ResponseEntity<?> updateUserData(@RequestBody GreenBusUser updatedUserDetails, Authentication authentication) { // Fetch the current authenticated user from the Principal GreenBusUser currentUser = (GreenBusUser) authentication.getPrincipal(); // Update the name fields with the new values currentUser.setFirstName(updatedUserDetails.getFirstName()); currentUser.setLastName(updatedUserDetails.getLastName()); // Save the updated user to your database (use your existing repository) userRepository.save(currentUser); // Refresh the Principal in the SecurityContext to reflect changes SecurityContextHolder.getContext().setAuthentication( new UsernamePasswordAuthenticationToken( currentUser, // Pass the updated user object authentication.getCredentials(), authentication.getAuthorities() ) ); return ResponseEntity.ok("User name updated successfully"); }
Key Notes:
- Ensure your
GreenBusUserclass implementsUserDetails(required for it to be used as a Principal in Spring Security). - The
Authenticationparameter is automatically injected if your controller is within a Spring Security context.
2. Fixing the "No User Found" Exception in getUserObject()
This error typically means your getUserObject() method can’t retrieve the user after the update. Here are the most common fixes:
Possible Cause 1: The Update Didn’t Persist to the Database
- Verify your
userRepository.save(currentUser)call is committing changes. If using Spring Data JPA, ensure your repository method is annotated with@Transactional(or that the controller method has this annotation). - Double-check that
GreenBusUserhas a valid identifier (likeid) that your repository uses to locate the user.
Possible Cause 2: getUserObject() Uses an Outdated Query
If getUserObject() fetches the user via a field that’s not being updated (like username), confirm the query is working correctly. For example:
public GreenBusUser getUserObject() { String currentUsername = SecurityContextHolder.getContext().getAuthentication().getName(); GreenBusUser user = userRepository.findByUsername(currentUsername); if (user == null) { throw new RuntimeException("No user found"); } return user; }
- Ensure
findByUsernameis properly implemented and returns the updated user. If you’re caching user data, invalidate the cache after updating the user.
Possible Cause 3: The Principal Wasn’t Refreshed
If getUserObject() relies on the Principal instead of the database, failing to refresh the Principal (as shown in step 1) will cause it to use an outdated user instance. Make sure you update the SecurityContext after saving the user.
3. Ensuring the Welcome Message Updates
Your getPrincipalDisplay() method pulls the user from the SecurityContextHolder, so once you refresh the Principal, the next page load will automatically use the updated name:
public String getPrincipalDisplay(ModelMap modelMap) { GreenBusUser user = (GreenBusUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); String displayName = user.getFirstName() + " " + user.getLastName(); modelMap.addAttribute("welcomeMessage", "Welcome, " + displayName); return displayName; }
Final Quick Checks
- Test your AJAX endpoint with a tool like Postman to confirm the JSON body is parsed correctly and the user is updated in the database.
- Debug
getUserObject()to see exactly where it fails: is the username correct? Is the repository query returning null? - Confirm the
GreenBusUserin the Principal is the updated instance after the PUT request.
内容的提问来源于stack exchange,提问作者Kramer

