首页 > 解决方案 > 使激活链接不可过期

问题描述

我有一个关于通过电子邮件激活新帐户的问题。

我关注此注册 – 通过电子邮件激活新帐户

我的问题是关于

它将在创建后 24 小时内到期

@Entity
public class VerificationToken {
    private static final int EXPIRATION = 60 * 24;
[...]

我想知道我们是否可以确保链接没有过期时间,或者它是否没有良好的安全实践,为什么?

标签: javaspringspring-security

解决方案


只需进行此修改即可。

  1. 删除 2.1 上不再需要的属性和方法:
@Entity
public class VerificationToken {
    //private static final int EXPIRATION = 60 * 24;

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

    private String token;

    @OneToOne(targetEntity = User.class, fetch = FetchType.EAGER)
    @JoinColumn(nullable = false, name = "user_id")
    private User user;

    //private Date expiryDate;

    //private Date calculateExpiryDate(int expiryTimeInMinutes) {
        //Calendar cal = Calendar.getInstance();
        //cal.setTime(new Timestamp(cal.getTime().getTime()));
        //cal.add(Calendar.MINUTE, expiryTimeInMinutes);
        //return new Date(cal.getTime().getTime());
    //}

    // standard constructors, getters and setters
}
  1. 去掉示例 3.1.1 中注释的 if 语句(这样系统就不会验证是否过期):
@Autowired
private IUserService service;

@RequestMapping(value = "/regitrationConfirm", method = RequestMethod.GET)
public String confirmRegistration
  (WebRequest request, Model model, @RequestParam("token") String token) {

    Locale locale = request.getLocale();

    VerificationToken verificationToken = service.getVerificationToken(token);
    if (verificationToken == null) {
        String message = messages.getMessage("auth.message.invalidToken", null, locale);
        model.addAttribute("message", message);
        return "redirect:/badUser.html?lang=" + locale.getLanguage();
    }

    User user = verificationToken.getUser();
    //Calendar cal = Calendar.getInstance();
   // if ((verificationToken.getExpiryDate().getTime() - cal.getTime().getTime()) <= 0) {
     //   String messageValue = messages.getMessage("auth.message.expired", null, locale)
       // model.addAttribute("message", messageValue);
       // return "redirect:/badUser.html?lang=" + locale.getLanguage();
    //} 

    user.setEnabled(true); 
    service.saveRegisteredUser(user); 
    return "redirect:/login.html?lang=" + request.getLocale().getLanguage(); 
}

尽管这是完全可行的,但出于安全原因不建议这样做。正如用户第二所说,在Security StackExchange中,您将获得有关电子邮件确认背后安全性的适当响应。


推荐阅读