【发布时间】:2021-01-07 09:04:49
【问题描述】:
我想在 Spring 中使用 PreAuthorize 注解获取参数:
@RequestMapping(value = "/remove/{id}", method = RequestMethod.GET)
@PreAuthorize("#id != authentication.id")
public boolean remove(@PathVariable Long id) { ... }
但我得到一个错误:
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/Spring_sec4] threw exception [Request processing failed; nested exception is java.lang.IllegalArgumentException: Failed to evaluate expression '#id != authentication.id'] with root cause
org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'id' cannot be found on object of type 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken' - maybe not public?
怎么办?
我使用此代码在控制器方法中获取当前用户:
UserApp currentUserApp = (UserApp) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
然后
if ( currentUserApp.getId().equals(id) ) {
throw new Exception("You can't remove yourself");
}
【问题讨论】:
-
Authorization没有id属性。 -
谢谢,我该怎么做?你有想法吗?
-
id在这里是什么?你想检查什么。 -
id是用户类中的一个字段