【问题标题】:How to config Spring Security with JPA?如何使用 JPA 配置 Spring Security?
【发布时间】:2015-10-21 14:26:06
【问题描述】:

我需要将 Spring Security 添加到我的项目中。正确的方法是什么?我必须为他们创建实体 User 和 UserRole 以及 DAO 和 Services。我使用 EntityManager 来访问数据。我读到,我只需要为 UserDetails 编写实现,但我不知道如何正确地做到这一点。这是我的代码:

用户.java

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@JsonProperty
private Integer id;
@Column(name = "username", length = 20, nullable = false)
@JsonProperty
private String username;
@Column(name = "password", nullable = false)
@JsonProperty
private String password;
@Column(name = "enabled", nullable = false)
@JsonProperty
private boolean enabled;
@Column(name = "email", nullable = false)
@JsonProperty
private String email;
@OneToMany(mappedBy = "user", cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
private Set<UserRole> userRoles;
//getters and setters

UserRole.java

 @Id
@GeneratedValue(strategy = GenerationType.AUTO)
@JsonProperty
private Integer id;

@ManyToOne(optional = false)
@JoinColumn(name = "user_ID", referencedColumnName = "id", foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
private User user;

@Column(name="role")
@JsonProperty
private String role;
//getters and setters

我该怎么办?

【问题讨论】:

    标签: java spring spring-mvc jpa spring-security


    【解决方案1】:

    我写了一篇关于您正在寻找的内容的博客文章。看到这篇文章,我很确定它会回答你的问题:

    https://giannisapi.wordpress.com/2011/09/21/spring-3-spring-security-implementing-custom-userdetails-with-hibernate/

    在下面UserDetails的Service层,注意它从org.springframework.security.core.userdetails.UserDetailsS​​ervice中实现了UserDetailsS​​ervice。

    还有:

    loadUserByUsername 方法返回 assembler.buildUserFromUserEntity 的结果。简单地说,这个汇编器的方法所做的就是从给定的 UserEntity DTO 构造一个 org.springframework.security.core.userdetails.User 对象。 Assembler 类的代码如下:

    【讨论】:

      猜你喜欢
      • 2020-08-06
      • 1970-01-01
      • 2011-07-19
      • 2013-11-01
      • 2014-02-09
      • 1970-01-01
      • 2014-09-22
      • 1970-01-01
      • 2011-02-10
      相关资源
      最近更新 更多