【问题标题】:how to can get paremeters with @PreAuthorize in Spring security如何在 Spring 安全性中使用 @PreAuthorize 获取参数
【发布时间】: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是用户类中的一个字段

标签: java spring security


【解决方案1】:

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) { ... }

【讨论】:

    猜你喜欢
    • 2016-11-16
    • 2015-06-20
    • 2017-11-23
    • 1970-01-01
    • 2017-01-10
    • 2020-07-06
    • 2013-05-01
    • 2019-03-03
    • 2016-08-11
    相关资源
    最近更新 更多