我正在努力學習Spring.我使用以下工具使用Spring Boot創(chuàng)建了一個項目:
> Spring Data JPA > Spring Data REST >春天的HATEOAS >春季安全
我正在嘗試創(chuàng)建一個用戶實體.我希望用戶擁有加密密碼(鹽).
當我對/ api / users進行POST時,我成功創(chuàng)建了一個新用戶.
{
"firstname":"John",
"lastname":"Doe",
"email":"johndoe@example.com",
"password":"12345678"
}
但我有兩個問題:
>密碼以明文形式保存 >鹽是空的
06001
我認為問題是使用默認構(gòu)造函數(shù)而不是我創(chuàng)建的另一個.我是Spring和JPA的新手,所以我必須遺漏一些東西.這是我的代碼.
User.java
@Entity
@Table(name = "users")
public class User{
@Id
@GeneratedValue
private Long id;
@Column(nullable = false)
public String firstname;
@Column(nullable = false)
public String lastname;
@Column(nullable = false, unique = true)
public String email;
@JsonIgnore
@Column(nullable = false)
public String password;
@JsonIgnore
@Column
private String salt;
public User() {}
public User(String email, String firstname, String lastname, String password) {
this.email = email;
this.firstname = firstname;
this.lastname = lastname;
this.salt = UUID.randomUUID().toString();
this.password = new BCryptPasswordEncoder().encode(password this.salt);
}
@JsonIgnore
public String getSalt() {
return salt;
}
@JsonProperty
public void setSalt(String salt) {
this.salt = salt;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
@JsonIgnore
public String getPassword() {
return password;
}
@JsonProperty
public void setPassword(String password) {
this.password = password;
}
}
UserRepository.java
public interface UserRepository extends JpaRepository<User, Long> {
public User findByEmail(String email);
public User findByEmailAndPassword(String email, String password);
}
Application.java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application .class, args);
}
}
此外,如果有人發(fā)現(xiàn)我做錯了什么,我想指出我應(yīng)該把用戶登錄代碼放在哪里/如何(解密).
謝謝. 解決方法: 所以,這就是我如何解決我的問題:我創(chuàng)建了一個Controller作為我的自定義端點,然后我創(chuàng)建了一個服務(wù),在其中我放置了我想要創(chuàng)建用戶的邏輯.這是代碼:
UserController.java
@Controller
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/api/register")
@ResponseBody
public Long register(@RequestBody User user) {
return userService.registerUser(user);
}
...
}
UserService .java
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public Long registerUser(User user) {
user.setPassword(new BCryptPasswordEncoder().encode(password));
userRepository.save(user);
return user.getId();
}
...
}
所以通過POST來做
{
"firstname":"John",
"lastname":"Doe",
"email":"johndoe@example.com",
"password":"12345678"
}
在/ api / register中,我現(xiàn)在可以創(chuàng)建一個帶有哈希密碼的用戶. 來源:http://www./content-4-198301.html
|