如何在springsecurity中使用@preauthorize获取参数

9rnv2umw  于 2021-06-26  发布在  Java
关注(0)|答案(1)|浏览(693)

我想在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");
}
z9ju0rcb

z9ju0rcb1#

Authorization 没有一个 id 属性。
你需要实施 org.springframework.security.core.userdetails.UserDetails 有一个 id 字段:https://stackoverflow.com/a/39931142/2039546
您可以稍后通过键入 authentication.principal.id .

@RequestMapping(value = "/remove/{id}", method = RequestMethod.GET)
@PreAuthorize("#id != authentication.principal.id")
public boolean remove(@PathVariable Long id) { ... }

相关问题