Jwt+asp.net MVC timestamp prevents replay attacks

Source: Internet
Author: User

Time Stamp effect

The client makes a request to the server-side interface and, if the request information is encrypted, is intercepted by a third party to the request packet, which can be used to repeat the request operation. If the service side does not perform anti-replay attacks, the server pressure increases, and the use of timestamps to solve the problem.


The previous article described the JWT Security verification operation, which now combines a timestamp for anti-duplication attacks and is intercepted by a third-party capture tool into the headers token for a mock request operation.


Tamper Proof

The general use of the way is to put the parameters splicing, the current project Appkey, the two sides agreed "key", added to the dictionary dictionary set, according to the ABCD order, and finally in md5+ encryption. The client sends the encrypted string along with the request parameter to the server. Server according to

When the above rules are spliced and encrypted, the comparison is equal to the encrypted string passed in.


Anti-re-use

The above way to encrypt, can not solve the problem of anti-multiplexing, then need to be generated in the client and the server UTC timestamp, this UTC is to prevent your client and the server is not in the same time zone, hehe, and then put the timestamp timestamp spell in the ciphertext, as to the effectiveness of anti-reuse

Get to the point below, code start


Create Descryption Help Class

Public class DESCryption
    {

        /// <summary>
        /// //Attention, it is 8 characters, 64 bits
        /// </summary>
        Private static string PrivateRsa = ConfigurationManager.AppSettings["PrivateRsa"];

        /// <summary>
        /// //Attention, it is 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>
        /// decrypt
        /// </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 the timestamp verification method to the Myauthorizeattribute

To pass the DESC signature time string as a request

If the incoming timestamp is less than the current time of the server returns false prompt permission is insufficient

If the incoming timestamp is greater than the current time of the server, return true to normal access


The perfect solution is to set the expiration time for Jwttoken in Redis. I wish I could add the whole thing,

Please leave a message-I will update GitHub in time to add this Dmeo complete


/ / Request parameters
            String requestTime = httpContext.Request["rtime"]; //Request time is signed by DESC
            If (string.IsNullOrEmpty(requestTime))
                Return false;


            / / Request time DESC decryption plus time stamping time is the effective time of the request
            DateTime Requestdt = DateTime.Parse(DESCryption.Decode(requestTime)).AddMinutes(int.Parse(TimeStamp));
            DateTime Newdt = DateTime.Now; //The current time the server receives the request
            If (Requestdt < Newdt)
            {
                Return false;
            }
            Else
            {
                //Do other operations
                Var userinfo = JwtHelp.GetJwtDecode(authHeader);
                //For example, generate jwtToken and store it in redis.
                / / This place uses jwtToken as the key to get the entity val and then see if jwtToken is the same according to redis
                If (userinfo.UserName == "admin" && userinfo.Pwd == "123")
                    Return true;
            }



We also have what needs to understand the novice tutorial knowledge points, you can leave a message to me. I will write a simple teaching demo for you in three days.

Post-ASP. NET Api,asp.net Core,java tutorials are available.

Https://github.com/yaols/JWT.MvcDemo


Jwt+asp.net MVC timestamp prevents replay attacks

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.