【问题标题】:User class for Spring Security applicationSpring Security 应用程序的用户类
【发布时间】:2018-12-15 12:36:06
【问题描述】:

我目前正在开发一个带有 JPA/Hibernate 和 Angular 2 前端的多用户 Spring Boot 应用程序。我设想两种基本类型的用户:供应商和客户。

在开始编码之前,我用类User 和两个子类CustomerVendor 制作了一个UML 类图。子类的原因是它们具有不同的属性:例如供应商应该能够写出关于他自己的一般描述,而客户应该能够保存收藏夹。

下图是我的类图的摘录:

由于这是我的第一个具有登录/注册功能的应用程序,我开始阅读有关如何使用 Spring Security 实现登录和注册功能的教程。随着时间的推移,我不得不意识到基本上所有的样本都只包含一个User 类,其权限取决于他的Roles,这通常是实现上述功能的推荐/需要的类。

在我看来,User 类并不意味着有子类,但教程和示例自然大多涵盖基本设置,而不是代表具有完全不同用户的复杂业务模型。

我的问题如下:创建User 类的子类是否可行且可取,我想使用自定义UserDetailsService 类进行授权?如果没有,您是否建议将CustomerVendor 类中的属性合并到User 类中,从而确定User 的角色是否应该能够具有某个属性,否则它将只是为空?

提前非常感谢!

【问题讨论】:

  • 你可以使用任何扩展 UserDetails 的类,没有问题。 Spring Security 只是抓取从您的 UserDetailService 返回的 UserDetails 实现,并将其放置到安全上下文中。但是我认为如果您将使用很少的 userdetails 实现进行操作,那将不会那么方便=)

标签: java spring spring-security architecture


【解决方案1】:

Spring 安全性使用UserDetailsService 接口进行身份验证和授权功能。您应该实现loadUserByUsername 函数以从数据库或内存或任何地方加载User

Spring 安全工作以UserDetails 接口为模型。因此,您的 User 实体需要实现 Spring Security 可以使用的 UserDetails 接口。

现在,您拥有可以像其他实体一样继承的 User 实体,您可以使用 @Inheritance 对其进行注释,如下所示:

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class User implements UserDetails {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Length(min=5)
    private String password;
    private String username;

    @Email
    private String email;
    private String phoneNumber;
    private boolean enabled;
    private boolean verified;

    @ManyToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
    private Set<Authority> roles= new HashSet<>();

    //...
}

@Entity
public class Vendor extends User{
        private String name;
        private String description;
        private Date openingTime;
        private Date closingTime;
        @ManyToOne
        private List<File> images;
        //...
}

@Entity
public class Customer extends User{
        private String forename;
        private String surname;
        @ManyToOne
        private List<PaymentDetails> paymentDetailsList;
        //...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-28
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    • 2011-01-17
    • 1970-01-01
    • 2015-10-26
    • 2013-10-05
    相关资源
    最近更新 更多