我尝试使用Spring Security保护我的REST端点,同时坚持@RepositoryRestResource
的魔力。
虽然保护存储库方法没问题,但我正在努力保护相对链接。
我试图坚持使用@RepositoryRestController
并映射其中的每个URL端点,但是我认为必须有一个更简单的解决方案。
{
"_embedded": {
"users": [
{
"id": 1,
"firstName": "Xavier",
"lastName": "Tester",
"username": "test",
"_links": {
"self": {
"href": "http://localhost:8080/api/v1/users/1"
},
"user": {
"href": "http://localhost:8080/api/v1/users/1"
},
"roles": {
"href": "http://localhost:8080/api/v1/users/1/roles"
}
}
}
]
},
"_links": {
"self": {
"href": "http://localhost:8080/api/v1/users"
},
"profile": {
"href": "http://localhost:8080/api/v1/profile/users"
},
"search": {
"href": "http://localhost:8080/api/v1/users/search"
}
}
}
@RepositoryRestResource
public interface UserRepository extends CrudRepository<User, Long>
{
@PostFilter("hasPermission(filterObject.id, 'READ_USER')")
Iterable<User> findAll();
@PreAuthorize("hasPermission(#id, 'READ_USER')")
Optional<User> findById(Long id);
}
@RepositoryRestResource
public interface RoleRepository extends CrudRepository<Role, Long>
{
@PostFilter("hasPermission(filterObject.id, 'READ_ROLE')")
Iterable<Role> findAll();
@PreAuthorize("hasPermission(#id, 'READ_ROLE')")
Optional<Role> findById(Long id);
}
因此,我有一个用户test
,该用户具有READ_USER
的权限,但没有READ_ROLE
的权限。
到目前为止,当我尝试访问/roles
或/roles/1
时,我收到403 Access Denied。
但是当我访问链接/users/1/roles
时,请求被允许。