JWT + asp.net MVC timestamp to prevent replay attack

Time:2019-11-29

Time stamp function

The client is requesting from the server interface. If the request information is encrypted and intercepted by the third party, the request package can be used for repeated request operations. If the server does not carry out anti replay attack, the server pressure will increase, and the use of timestamp can solve this problem.

The last article talked about the JWT security verification operation. Now it combines the time stamp to prevent repeated attacks and the third-party packet grabbing tool to intercept the token in headers to simulate the request operation.

Tamper proofing

The general way is to splice the parameters. The current project appkey, the “key” agreed by both parties, is added to the dictionary set, sorted according to the order of ABCD, and finally encrypted in MD5 +. The client sends the encrypted string and the request parameters to the server together. Server according to

After the above rules are spliced and encrypted, is it equal to the encrypted string passed in

Anti multiplexing

The above encryption method can’t solve the problem of anti multiplexing. At this time, you need to generate UTC timestamps on the client and the server respectively. This UTC is to prevent your client and the server from being in the same time zone. Ha ha, then put timestamp in the ciphertext. As for the effectiveness of anti multiplexing

Let’s go to the main topic and start the coding

Create descryption help class

public class DESCryption
 {

 /// <summary>
 ///// note, it's 8 characters, 64 bits
 /// </summary>
 private static string PrivateRsa = ConfigurationManager.AppSettings["PrivateRsa"];

 /// <summary>
 ///// note, it's 8 characters, 64 bits
 /// </summary>
 private static string PublicRsa = ConfigurationManager.AppSettings["PublicRsa"];

 /// <summary>
 // / encryption
 /// </summary>
 /// <param name="data"></param>
 /// <returns></returns>
 public static string Encode(string data)
 {
 byte[] byKey = Encoding.ASCII.GetBytes(PrivateRsa);
 byte[] byIV = Encoding.ASCII.GetBytes(PublicRsa);

 DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
 int i = cryptoProvider.KeySize;
 MemoryStream ms = new MemoryStream();
 CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);

 StreamWriter sw = new StreamWriter(cst);
 sw.Write(data);
 sw.Flush();
 cst.FlushFinalBlock();
 sw.Flush();
 return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);

 }

 /// <summary>
 // / decryption
 /// </summary>
 /// <param name="data"></param>
 /// <returns></returns>
 public static string Decode(string data)
 {
 byte[] byKey = Encoding.ASCII.GetBytes(PrivateRsa);
 byte[] byIV = Encoding.ASCII.GetBytes(PublicRsa);

 byte[] byEnc;
 try
 {
 byEnc = Convert.FromBase64String(data);
 }
 catch
 {
 return null;
 }

 DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
 MemoryStream ms = new MemoryStream(byEnc);
 CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
 StreamReader sr = new StreamReader(cst);
 return sr.ReadToEnd();
 }
 }

Then add a timestamp to myauthorizeattribute to verify the method

Pass in desc signature time string as request

If the time stamp passed in is less than the current time of the server, false will be returned. Insufficient permission will be prompted

If the time stamp passed in is greater than the current time of the server, return true to access normally

The perfect solution is to set the expiration time of jwttoken in redis. You guys want me to add it completely,

Please leave a message — I will update GitHub in time to complete this dmeo

//Request parameters
 String requesttime = httpcontext. Request ["rtime"]; // the request time is signed by desc
 if (string.IsNullOrEmpty(requestTime))
 return false;


 //Request time: the effective time of the request is the time stamped after desc decryption
 DateTime Requestdt = DateTime.Parse(DESCryption.Decode(requestTime)).AddMinutes(int.Parse(TimeStamp));
 Datetime newdt = datetime. Now; // the current time when the server receives the request
 if (Requestdt < Newdt)
 {
 return false;
 }
 else
 {
 //Other operations
 var userinfo = JwtHelp.GetJwtDecode(authHeader);
 //For example, generate jwttoken and store it in redis 
 //This place uses jwttoken as key to get entity Val, and then check whether jwttoken is the same according to redis
 if (userinfo.UserName == "admin" && userinfo.Pwd == "123")
  return true;
 }

What else do you need to know about the novice tutorial knowledge points, you can leave a message to me. I will write a simple teaching demo to you in three days

Later asp.net API, asp.net core and java tutorial are all available.

Https://github.com/yaols/jwt.mvcdemo (local download)

summary

The above is the whole content of this article. I hope that the content of this article has a certain reference learning value for everyone’s study or work. If you have any questions, you can leave a message and exchange. Thank you for your support for developepaar.