我正在优化Web应用程序的身份验证过程,该Web应用程序的前端是使用Angular编写的,而后端API是用Spring Boot编写的。我需要为我的用户生成一个密码,并在注册时将其发送到他们的电子邮件中。我需要从哪里开始才能实现这一目标?应该从前端还是后端完成?
我创建了一个Util类,其中有一个生成密码的方法,以及User的相应实体类(其中包含密码和电子邮件字段)。我不知道如何从这里继续。
我的代码如下:
用户模型类:
@Entity
@Table(name="users")
public class User extends BaseModel{
@Column(name="email")
private String email;
@Column(name="first_name")
private String firstName;
@Column(name="fullname")
private String fullName;
@Column(name="password")
private String password
用户服务类:
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public List<User> getUsers() {
return userRepository.findAll();
}
public User authUser(User user) throws Exception {
//System.out.println(user.getPassword());
System.out.println("User Password####"+user.getPassword());
System.out.println("User Username####"+user.getUsername());
return `userRepository.findByUsernameAndPassword(user.getUsername(),AES.encrypt(user.getPassword()));
}
public User addUser(User user) {
// TODO Auto-generated method stub
return userRepository.save(user);
}
public User findByUsername(String username) {
// TODO Auto-generated method stub
return userRepository.findByUsername(username);
}
public List<UsersToVerify> getUsersToVerify() {
// TODO Auto-generated method stub
return userRepository.getUsersToVerify();
}
public int verifyUsers(Long userId) {
// TODO Auto-generated method stub
return userRepository.approveUsers(userId);
}
}
util类:
public String randomPassword() {
System.out.println("Generating Password");
String ALPHA_NUMERIC_STRING = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&?{}*";
StringBuilder builder = new StringBuilder();
int count = 8;
while (count-- != 0) {
int character = (int) (Math.random() * ALPHA_NUMERIC_STRING.length());
builder.append(ALPHA_NUMERIC_STRING.charAt(character));
}
return builder.toString();
}
答案 0 :(得分:1)
我使用spring-boot-starter-mail遵循此主题,它与我合作。
您可以更新方法authUser()中的代码,以使用EmailService通过电子邮件发送生成的密码。
将依赖项添加到pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
创建EmailService发送电子邮件。
@Component
public class EmailServiceImpl implements EmailService {
@Autowired
public JavaMailSender emailSender;
public void sendSimpleMessage(
String to, String subject, String text) {
...
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(text);
emailSender.send(message);
...
}
}