Updating user info with JWT on spring security app

459 views Asked by At

I am working on a simple REST API using spring security with a JWT Filter. However, I am a little bit confused with how to update user info.

After loggin in I get a JWT that I use to make request on other endpoints. But how do I create a controller that create or update data? I have my user table and my preferences table they are one to one related. If I make a request like "/create/preferences" what do I put in the body in order for me to create a preference link to this user making the call to the api?

   
   @PostMapping("/user/preferences")
   public ResponseEntity<Preferences> getUserPreferences() {
       /*
what to put here
*/
       return new ResponseEntity<>(HttpStatus.OK);
   }    

Do I have to get the user from the token? Then I can create a preference object with this user id?

Thanks in advance

1

There are 1 answers

2
Art On
@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @PutMapping("/{id}")
    public ResponseEntity<?> updateUser(@PathVariable Long id, @RequestBody User user) {
        // Use Spring Security to get the authenticated user from the security context
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User authenticatedUser = (User) authentication.getPrincipal();

        // Verify that the authenticated user is the same as the user being updated
        if (!authenticatedUser.getId().equals(id)) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }

        // Update the user information
        user.setId(id);
        userService.updateUser(user);

        return ResponseEntity.ok().build();
    }
}

What do you think about this? UserService would be responsible for actually updating the user in the database. The controller simply handles the request, authenticates the user with JWT, and checks that the authenticated user is authorized to make the update.

You can change the ResponseEntity type as you like.