问题描述:

For a url like

@RequestMapping(value = "/users/{userId}/update/password", method = RequestMethod.PUT)

how to be sure the connected user can modify only its password and not the one of other user...

actually, i have protection on url... but it's not enough to prevent this case

http.authorizeRequests().antMatchers("/rest/users/**").hasRole("USER");

网友答案:

I soppuse you have a authentication over /rest/users/**. You can get current user with the following code.

YourUserPrincipalDto dto = (YourUserPrincipalDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Long userId = dto.getUserId();

YourUserPrincipalDto should implements UserDetails.

网友答案:

Assuming that you have a Spring bean with a public method with username as one of the arguments (it can be in controller, security layer, service layer or DAO), you can add a @PreAuthorize annotation:

@PreAuthorize("#username == authentication.name")
public void updateUserPassword(String username, String newPassword);

You must enable pre- and post-annotations in your security config if not already done so.

网友答案:

Add the Principal object (like here) to your method's argument list to confirm that the authenticated user is the same user as the userId in the API URL (do whatever background DAO queries are necessary to map between the userId and the authenticated user). Return a 403 or 404 if it is not, otherwise update the password. Whether you return 403 or 404, best to be consistent and return the same number for both unauthorized and user-not-found situations in order to not provide unwanted information to hackers.

相关阅读:
Top