程序问答   发布时间:2022-05-31  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了spring-boot中如何实现行级授权?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决spring-boot中如何实现行级授权??

开发过程中遇到spring-boot中如何实现行级授权?的问题如何解决?下面主要结合日常开发的经验,给出你关于spring-boot中如何实现行级授权?的解决方法建议,希望对你解决spring-boot中如何实现行级授权?有所启发或帮助;

假设我在 spring boot 中有以下端点

GET /todo

deletE /todo/{ID}

如何确保只返回 userID 的条目,并且用户只能更新自己的待办事项? 我有一个填充的 Authentication 对象。 我可以使用任何构建方式吗?或者只是确保始终调用 findXyzByIDAndUserID,其中始终从 Principal 检索用户 ID?

我有点担心可能会忘记检查并显示其他用户的条目。

解决方法

我的方法是 3 种方式实现:(使用 jpa 和休眠)

  • 用户请求上下文
  • 用于获取上下文的映射超类
  • 用于注入用户 ID 的语句检查器

例如:

public final class UserrequestContext {
  public static String getUserId() {
    // code to retrieve your userid and throw when there is none!
    if (userId == null) throw new IllegalStateException("userid null");
    return userId;
  }
}
@mappedSuperclass
public class UserResolver {
  public static final String user_RESOLVER = "user_RESOLVER";

  @Access(AccessType.PROPERTY)
  public String getUserId() {
    return UserrequestContext.getUserId();
  }

}
@Component
public class UserInspector implements StatemenTinspector {
  @Override
  public String inspect(String statement) {
    if (statement.contains(UserResolver.user_RESOLVER)) {
       statement = statement.replace(UserResolver.user_RESOLVER,"userId = '" + UserrequestContext.getUserId() + "'" );
    }
    return sql;
  }

  @Bean
  public HibernatePropertyCustomizer hibernatePropertyCustomizer() {
    return hibernateProperies -> hibernateProperties.put("hibernate.session_factory.statement_inspector",UserInspector.class.getName());
  }
}

所以你的实体看起来像这样

@Entity
...
@Where(clause = UserResolver.user_RESOLVER)
public class Todo extends UserResolver {
   ...
}

大佬总结

以上是大佬教程为你收集整理的spring-boot中如何实现行级授权?全部内容,希望文章能够帮你解决spring-boot中如何实现行级授权?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: