如何使用JPA配置Spring Security?

时间:2015-07-30 09:39:06

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

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

User.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

我该怎么办?

1 个答案:

答案 0 :(得分:0)

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

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类的代码如下: