Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Security: allow user only to access their own administration page

In my web app users are able to change their user details. The URL for this page is:

springproject/usermanagement/edituserinfo/4

where "4" is the user id.

My security-context looks like:

<security:http auto-config="true" use-expressions="true">
    <security:intercept-url pattern="/usermanagement" access="isAuthenticated()" />
    <security:intercept-url pattern="/usermanagement/new" access="hasRole('ROLE_ADMIN')" />
    <security:intercept-url pattern="/usermanagement/edit/*" access="hasRole('ROLE_ADMIN')" />
    <security:intercept-url pattern="/usermanagement/edituserinfo/*" access="isAuthenticated()" />  
</security:http>

How can I restrict the user only to access their own "edituserinfo" page? E.g. user with user id 1 can only access: "springproject/usermanagement/edituserinfo/1 " and not "springproject/usermanagement/edituserinfo/4 "

like image 497
jorgen Avatar asked Jul 29 '11 09:07

jorgen


2 Answers

You can also accomplish this using Spring Security's @PreAuthorize which supports expressions:

@PreAuthorize("#userId == principal.id")
public void doSomething(@PathVariable String userId);

See the Spring docs:

Access Control using @PreAuthorize and @PostAuthorize

like image 196
dbmargo Avatar answered Sep 29 '22 12:09

dbmargo


Use a PathVariable on the URL, like @RequestMapping("/usermanagement/edituserinfo/{userid}") and in your code validate the logged-in user's Spring Security context principle (via SecurityContextHolder.getContext().getAuthentication().getPrincipal()) against the userid path variable. If they don't match, bounce the user out, log a SecurityException, and send an email to the admins.

like image 22
atrain Avatar answered Sep 29 '22 11:09

atrain