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

Sending the web token to the client

In the previous section, I explained what a web token consists of and how you can generate it from your Delphi code. In this section, we will talk about how that token is sent to the client for further use and information sharing across different microservices.

Remember the unit we created for the token generation that had the method GetTokenFromData? Well, we are going to use that unit in our micro services controller to generate a new token for the first time when then client logs in and pass it along to the client. We are also going to configure the message in a way that our token gets passed along to other microservices in the same group to give the user a unified login experience across multiple services.

Here’s what the code in the controller looks like followed by the explanation:

I am going assume that you are familiar with Delphi MVC controllers so I am going to focus on explaining the code that connected with the token only.

The above code simply prepares the data we want to send to the user and then generates the web token from it (already explained in the last section). Next is the cookie preparation:

The above code adds a cookie to the response. This cookie will be stored by the browser and will be automatically be sent from the client to the server in the next request. At this point, lets delve into the cookie properties a bit. The Expires property tell the client when the cookie will expire. In our case, the value of 0 ensure that the cookie is valid only for the session of the browser and will be removed once the browser is closed. The Domain mentions the domain for which this cookie is set so the browser knows for which domain to send the cookie in the request. The Name is well.. the name which is useful to identify the cookie on the server side. The Path also specifies that the cookie only valid for a certain path within the domain. So if the request path doesn’t match the cookie path (even within the domain), the cookie will not be sent. Finally, the Value is the actual data of the cookie, which in our case is the web token.

Finally, we send response using the Render method. DMVC will automatically package the cookie in the response. Here’s what the client side response header looks like (after the server has responded). You can see that our token is present in the header and that the cookie has been set.

In the next section, I will show you how to use this token across other microservices.

One Reply on “Managing session information in web tokens in Delphi MVC Framework (Part 4)”

  1. Un tema muy interesante y muy bien explicado, por lo menos para mi que apenas me inicio en el desarrollo web

Leave a Reply

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