Managing session information in web tokens in Delphi MVC Framework (Part 3)

Implementing the solution in Delphi

In the previous section of this series, we delved into the concepts of encoding data and hashing it. In this section, we will write some code to implement what we understood.

Like I mentioned before, a web token will consist of two components

  • Encoded Data
  • Hash string

Lets implement a helper function that generates the above web token for us. This is what it should look like:

Code explanation

Its pretty obvious that I have created a new unit called ‘untTokenHelper.pas‘. The next, I use the required units from the beautiful RTL. System.NetEncoding unit contain TBase64Encoding which will help us convert our json data string to encoded data string and the System.Hash unit will help us generate the hash string from the encoded data string using our SecretKey.

The code is pretty straight forward. We create the TBase64Encoding class with the parameter 0. This tells the class that we do not want any restrictions on the length of the encoded data to add a new line.

Next we call the class’ Encode function passing it the json string as a parameter

We then take the encoded string and our secret key to generate a unique hash string.

Finally, we combine both (the encoded data and the hash string) by placing a . in between and return the result to the caller of the function.

In the next section, I will explain how to use the above unit to send the web token via cookie in the response of your controller’s action.

Leave a Reply

Your email address will not be published. Required fields are marked *