我遇到的问题是SpEL在此存储库的第二个方法中将实体参数作为空引用进行评估。第一种方法效果很好,id应该正确评估为Long。
@NoRepositoryBean
public interface SecuredPagingAndSortingRepository<T extends AuditedEntity, ID extends Serializable>
extends PagingAndSortingRepository<T, ID> {
@Override
@RestResource(exported = false)
@PreAuthorize("hasPermission(#id, null, 'owner')")
void delete(ID id);
@Override
@PreAuthorize("hasPermission(#entity, 'owner')")
void delete(T entity);
}
这是我的自定义PermissionEvaluator:
@Slf4j
@Component
public class CustomPermissionEvaluator implements PermissionEvaluator {
private final PermissionResolverFactory permissionResolverFactory;
@Autowired
public CustomPermissionEvaluator(PermissionResolverFactory permissionResolverFactory) {
this.permissionResolverFactory = permissionResolverFactory;
}
@Override
public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
Assert.notNull(userDetails, "User details cannot be null");
Assert.notNull(targetDomainObject, "Target object cannot be null");
log.debug("Permmission: " + permission + " check on: " + targetDomainObject + " for user: " + userDetails.getUsername());
PermissionType permissionType = PermissionType.valueOf(((String) permission).toUpperCase());
return permissionResolverFactory.getPermissionResolver(permissionType).resolve(targetDomainObject.getClass(), authentication, (AuditedEntity) targetDomainObject);
}
@Override
public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
// TODO
return false;
}
}
由于断言在CustomPermissionEvaluator中目标对象不能为null,因此该测试未通过。
@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
@ContextConfiguration(classes = SqapApiApplication.class)
public class PermissionsIT {
@Autowired
private TestGroupRepository testGroupRepository;
@Autowired
private UserRepository userRepository;
UserEntity user;
@Before
public void before() {
user = new UserEntity("user", "password1", true, Sets.newHashSet(RoleType.ROLE_USER));
user = userRepository.save(user);
}
@Test
@WithMockUser(username="user")
public void shouldDeleteWhenIsOwner() throws Exception {
TestGroupEntity testGroupEntity = new TestGroupEntity("testGroup", "testdesc", Sets.newHashSet(new AbxTestEntity(1, "abx", "desc", null)));
user.addTestGroup(testGroupEntity);
user = userRepository.save(user);
TestGroupEntity createdEntity = testGroupRepository.findAll().iterator().next();
testGroupRepository.delete(createdEntity);
}
}
答案 0 :(得分:5)
在接口中引用spel的方法参数时,需要使用Spring Data的@Param
注释它们以明确命名它们:
@PreAuthorize("hasPermission(#entity, 'owner')")
void delete(@Param("entity") T entity);
如果参数没有注释,Spring必须使用反射来发现参数名称。这仅适用于接口方法
-parameters
标志对于类方法,Spring有另一个选项 - 它可以使用调试信息。这适用于Spring 3和早期版本的Java,但它又依赖于编译时标志来工作(即-g
)。
为了便于携带,最好注释您需要引用的所有参数。