我想在spring中获取带有预授权注解的参数:
@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");
}
1条答案
按热度按时间z9ju0rcb1#
Authorization
没有一个id
属性。你需要实施
org.springframework.security.core.userdetails.UserDetails
有一个id
字段:https://stackoverflow.com/a/39931142/2039546您可以稍后通过键入
authentication.principal.id
.