Java Implements Message Retrieval Password Function

  • 2021-06-28 12:34:30
  • OfStack

The specific code of Java to achieve the function of retrieving password for mail is shared for your reference, which is as follows:

1. There is a need to retrieve the password by mailbox after forgetting it.Now the system will force the entry of mailbox at the time of registration. The first purpose is to retrieve the password through mail binding.I won't say anything about the function of sending email through java, but focus on finding your password.

2. Refer to other people's ideas: Send e-mail_URL in request e-mail_Verify url{Verify successful password modification, unsuccessfully jump to the failed page}

The focus is on how to generate this url and how to parse this url.
It is important to note that an url can only change its password once. When sending multiple messages with the same account number, only the last one has url

3. Encryption can prevent forgery attacks, url can only authenticate once and bind users.Generate url: Random keys can be generated using UUID.

Digital Signature= MD5 (User name +'$'+ Expiration time +'$' + Key key)

Database field (user name (primary key), key key, expiration time)

url parameter (user name, digital signature), generation of key key: Generate a key key for each user when they retrieve their password, url example: http://localhost:8080/user/reset_password ?sid=D622D6A23FBF86FFE696B593D55351A54AEAEA77 & userName=test4

Generate expiration time, generate digital signature, generate url, send mail.saveOrUpdate (user name, key key, expiration time)

The following is the springMvc code


@RequestMapping(value = "/user/i_forget_password")

@ResponseBody

public
Map forgetPass(HttpServletRequest request,String userName){
 Users users = userService.findUserByName(userName);
 Map map = new
HashMap<String ,String >();
 String msg = "";
 if(users == null){    // user name does not exist 
  msg = " user name does not exist , You won't forget your username ?";
  map.put("msg",msg);
  return
map;

 }

 try{

  String secretKey= UUID.randomUUID().toString(); // secret key 

  Timestamp outDate = new
Timestamp(System.currentTimeMillis()+30*60*1000);//30 Expires in minutes 

  long
date = outDate.getTime()/1000*1000;     // Ignore milliseconds 

  users.setValidataCode(secretKey);
  users.setRegisterDate(outDate);
  userService.update(users); // Save to database 
  String key = users.getUserName()+"$"+date+"$"+secretKey;
  String digitalSignature = MD5.MD5Encode(key);     // digital signature 
  String emailTitle = " Square Cloud Password Retrieved ";
  String path = request.getContextPath();
  String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  String resetPassHref = basePath+"user/reset_password?sid="+digitalSignature+"&userName="+users.getUserName();
  String emailContent = " Do not reply to this message . Click on the link below , Reset Password <br/><a href="+resetPassHref +" rel="external nofollow" target='_BLANK'> Click on me to reset the password </a>" +

    "<br/>tips: This message exceeds 30 Minute , Links will fail and need to be reapplied ' Retrieve password '"+key+"\t"+digitalSignature;

  System.out.print(resetPassHref);
  SendMail.getInstatnce().sendHtmlMail(emailTitle,emailContent,users.getEmail());

  msg = " Operation Successful , A retrieved password link has been sent to your mailbox.Please 30 Reset password in minutes ";

  logInfo(request,userName," Request to retrieve your password ");

 }catch
(Exception e){

  e.printStackTrace();

  msg=" Mailbox does not exist?unknown error , Contact the administrator. ";

 }

 map.put("msg",msg);

 return
map;

}

The retrieved link has been sent to the mailbox.Enter Mailbox Point to Open Link

Below is the link verification code to verify that if you jump to the modify password interface, you jump to the failed interface


@RequestMapping(value = "/user/reset_password",method = RequestMethod.GET)

 public
ModelAndView checkResetLink(String sid,String userName){

  ModelAndView model = new
ModelAndView("error");

  String msg = "";

  if(sid.equals("") || userName.equals("")){
   msg=" Incomplete Link , Please regenerate ";
   model.addObject("msg",msg) ;
   logInfo(userName," Failed retrieve password link ");
   return
model;

  }

  Users users = userService.findUserByName(userName);
  if(users == null){
   msg = " link error , Unable to find a matching user , Please re-apply to retrieve your password .";
   model.addObject("msg",msg) ;
   logInfo(userName," Failed retrieve password link ");
   return
model;

  }

  Timestamp outDate = users.getRegisterDate();
  if(outDate.getTime() <= System.currentTimeMillis()){   // Indicates expired 
   msg = " Link has expired , Please re-apply to retrieve your password .";

   model.addObject("msg",msg) ;

   logInfo(userName," Failed retrieve password link ");

   return
model;

  }

  String key = users.getUserName()+"$"+outDate.getTime()/1000*1000+"$"+users.getValidataCode();   // digital signature 
  String digitalSignature = MD5.MD5Encode(key);
  System.out.println(key+"\t"+digitalSignature);
  if(!digitalSignature.equals(sid)) {

   msg = " Incorrect link , Is it expired ? Re-apply ";

   model.addObject("msg",msg) ;

   logInfo(userName," Failed retrieve password link ");

   return
model;

  }

  model.setViewName("user/reset_password"); // Return to the interface for password change 
  model.addObject("userName",userName);

  return
model;

 }

Supplement 1: Timestamp objects lose millisecond precision when saved to data.For example: from 10-08, 2013 to 10:29:10.234, when it was stored in mysql database, it became from 10-08, 2013 to 10:29:10.0.Time becomes different and sid does not match equally.So I did an operation that ignored accuracy.

Supplement 2: Resolve title Chinese random code under linux


sun.misc.BASE64Encoder enc = new
sun.misc.BASE64Encoder();

mailMessage.setSubject(MimeUtility.encodeText(mailInfo.getSubject(), "UTF-8", "B"));  // Solve linux mail title Random Code 

Supplement 3: Why not insert sid directly into the user table?When validating, directly compare sid to ok.


Related articles: