bernard deromme
bernard deromme

Reputation: 151

security to url for a user

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");

Upvotes: 0

Views: 85

Answers (3)

holmis83
holmis83

Reputation: 16604

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.

Upvotes: 1

Hamedz
Hamedz

Reputation: 726

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.

Upvotes: 0

Glen Mazza
Glen Mazza

Reputation: 788

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.

Upvotes: 0

Related Questions