2017-08-06 55 views
2

为了保护我的Web服务,我已经实现了基本的Spring Boot Security。我知道您可以授予某些用户角色的某些服务的访问权限,但是是否也可以授予指定用户的访问权限(用户可以是动态的)?如何配置Spring Boot Security,以便用户只能更新自己的配置文件

比方说,我们有一个社交应用,每个用户都有自己的配置文件。用下面的REST的服务,他们应该是唯一一个能够编辑配置文件:

@RestController 
public class UserController { 
    @RequestMapping(method = RequestMethod.PUT, path = "/user/{userId}", ...) 
    public UserDetails updateUserDetails(@PathVariable("userId") String userId) { 
     // code for updating the description for the specified user 
    }} 
} 

我怎样才能确保春季安全,只有用户本身可以更新他的个人资料?任何其他用户都应该被拒绝。有没有一种优雅的方式,你如何配置这种行为?

我试图在我的WebSecurityConfig中找到一个方法,但没有成功。

@Configuration 
@EnableWebSecurity 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 
    @Override 
     protected void configure(HttpSecurity http) throws Exception { 
      http 
        // configure authorization for urls 
        .authorizeRequests() 
        // grant access to all users for root path and /home 
        //.antMatchers("/", "/home").permitAll() 
        // here i would like to grant access in the way, that only the user is allowed to perform this request by calling url with his userId 
        .antMatchers(HttpMethod.PUT,"/user/<userId>").and().httpBasic(); 
     } 

什么是一种很好的方法来实现这种行为?

回答

3

我认为实现这样的最好方法是将Principal(包含登录该请求的用户的对象)注入控制器,然后检查用户标识或用户名是否匹配。

@RestController 
public class UserController { 
    @RequestMapping(method = RequestMethod.PUT, path = "/user/{userId}", ...) 
    public UserDetails updateUserDetails(@PathVariable("userId") String userId, Principal principal) { 

     CustomUserDetails userDetails = (CustomUserDetails) principal; 
     if (userDetails.getUserId().equals(userId)) { 
      // Update the user 
     } 
    }} 
} 

注意,如果你想添加的用户ID,您将需要一个定制UserDetails接口,因为它只在默认情况下提供的用户名。如果你想知道如何检查这个question

3

使用@PreAuthorize注释:

@PreAuthorize("#userId == principal.userId") 
@RequestMapping(method = RequestMethod.PUT, path = "/user/{userId}", ...) 
public UserDetails updateUserDetails(@PathVariable("userId") String userId) { 
    // code for updating the description for the specified user 
} 

这假定实现UserDetails接口的类有一个UserID属性。

相关问题