Apache Shiro提供了一个简单而强大的身份认证和授权框架,但不包含密码恢复功能。我们可以自行实现一个找回密码的功能。以下是一个简单示例:
public class AccountRealm extends AuthorizingRealm {
// ... other code ...
public void resetPassword(String email) {
Account account = getAccountByEmail(email);
// generate token
String token = ""; // TODO: generate a random token
// update account with token
account.setResetToken(token);
saveAccount(account);
// send email
sendResetPasswordEmail(email, token);
}
// ... other code ...
}
@Controller
@RequestMapping("/password-reset")
public class PasswordResetController {
@Autowired
private AccountRealm accountRealm;
@GetMapping
public String showPasswordResetForm(Model model) {
model.addAttribute("resetForm", new ResetForm());
return "password-reset";
}
@PostMapping
public String resetPassword(@ModelAttribute("resetForm") ResetForm resetForm, BindingResult result) {
if (result.hasErrors()) {
return "password-reset";
}
accountRealm.resetPassword(resetForm.getEmail());
return "redirect:/login?reset=true";
}
}
@Controller
@RequestMapping("/change-password")
public class ChangePasswordController {
@Autowired
private AccountRealm accountRealm;
@GetMapping("/{token}")
public String showChangePasswordForm(@PathVariable String token, Model model) {
Account account = accountRealm.getAccountByResetToken(token);
if (account