gpt4 book ai didi

java - 找不到基于 Spring Boot 表达式的访问控制属性

转载 作者:行者123 更新时间:2023-12-02 12:06:00 25 4
gpt4 key购买 nike

我正在使用 Spring-data-rest 公开一些实体,我想使用 Spring 表达式语言配置访问控制并进行预授权,以便用户只能操作属于他的实体。

我的主体对象在其用户名(字符串)中包含用户 ID,并且用户有一个属性 ID(长整型):

@Entity
@Table(name = "users")
@Getter
@Setter
public class User {

@Id
@Column(name = "user_id", nullable = false, updatable = false)
private Long id;

...

}

我的存储库如下所示:

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

@Override
@PreAuthorize("hasRole('ROLE_ADMIN')")
User findOne(Long id);

@Override
@PreAuthorize("#user.id == principal.username")
void delete(User user);

...

}

但是,当通过 id 1(主体在其用户名中包含此 id)的用户身份进行身份验证时调用 DELETE/users/1 时,我收到以下异常:

java.lang.IllegalArgumentException: Failed to evaluate expression '#user.id == principal.username'
...
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'id' cannot be found on null

我的表述是根据官方Spring documentation 。有人可以指出我在这里缺少什么吗?

编辑:我在我的存储库中添加了所有方法,因为它们似乎是相互关联的。

最佳答案

在您的类User中,您必须注意idprivate,因此您的代码应该调用公共(public)方法来获取用户ID ,所以它必须是这样的:

  @Override
@PreAuthorize("#user.getId() == authentication.getName()")
void delete(@RequestParam(name="user", required=true)User user);
.....

您还必须调用公共(public)方法才能从主体获取用户名。

另外,请注意,您可以调用安全检查函数来执行更多逻辑,例如:

  @Autowired
private SecurityCheck securityCheck;

................

@Override
@PreAuthorize("@securityCheck.check(#user,authentication)")
void delete(User user);

在SecurityCheck类中可以这样定义:

@Component
public class SecurityCheck {


public boolean check(User user, Authentication authentication) {
if(user == null)
return false;
if(user.getId().equals(authentication.getName()))
return true;
// more logic ...
return false;
}
}

关于java - 找不到基于 Spring Boot 表达式的访问控制属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46908825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com