And*_*ndy 3 spring spring-security spring-boot
我已经实现了基本的Spring Boot Security东西,以保护我的Web服务。我知道您只能向某些用户角色授予对某些服务的访问权限,但是也可以向特定用户授予访问权限(用户可以是动态的)吗?
假设我们有一个社交应用,每个用户都有自己的个人资料。使用以下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
}}
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能确保春季安全,只有用户自己才能更新其个人资料?任何其他用户都应被拒绝。有没有一种优雅的方法,如何配置这种行为?
我试图在我的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();
}
Run Code Online (Sandbox Code Playgroud)
什么是实施此行为的好方法?
使用@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
}
Run Code Online (Sandbox Code Playgroud)
这假设实现UserDetails接口的类具有 userId 属性。
我认为,实现此类目标的最佳方法是将Principal(包含为此请求登录的用户的对象)注入控制器,然后检查用户ID或用户名是否匹配。
@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
}
}}
}
Run Code Online (Sandbox Code Playgroud)
请注意,UserDetails如果要添加用户ID,则需要一个自定义界面,因为默认情况下它仅提供用户名。如果您想知道如何检查此问题。
| 归档时间: |
|
| 查看次数: |
682 次 |
| 最近记录: |