Spring Security: allow user only to access their own administration page
In my web app users are able to change their user details. The UR开发者_开发知识库L 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 "
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
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.
精彩评论