scieee AI-readable full text Open interactive document viewer

The role of an API gateway in a microservice architecture

Parente, Pedro Dias

Abstract

Nowadays, with the development of bigger and more complex applications, the architectural paradigm for application development is changing from a more traditional Monolithic approach to an architectural style called Microservices. In this more recent, and increasingly popular, style of developing applications, a tool that has also become increasingly more popular is API Gateways. In this thesis I explored these and a few other concepts on various examples, recording my experience, with the intent to create a guide on how to more efficiently implement these tools on to your own projects, facilitating the usually long and arduous process of researching, learning, and implementing new technologies into your work.

Full text

Universidade do Minho Escola de Engenharia Departamento de Informática Pedro Dias Parente The role of an API Gateway in a Microservice Architecture October 2022 Universidade do Minho Escola de Engenharia Departamento de Informática Pedro Dias Parente The role of an API Gateway in a Microservice Architecture Master dissertation Master Degree in Informatics Engineering Dissertation supervised by José Carlos Leite Ramalho October 2022 i AUTHOR COPYRIGHTS AND TERMS OF USAGE BY THIRD PARTIES This is an academic work which can be utilized by third parties given that the rules and good practices internationally accepted, regarding author copyrights and related copyrights. Therefore, the present work can be utilized according to the terms provided in the license bellow. If the user needs permission to use the work in conditions not foreseen by the licensing indicated, the user should contact the author, through the RepositóriUM of University of Minho. License provided to the users of this work Attribution-NonCommercial CC BY-NC https://creativecommons.org/licenses/by-nc/4.0/ ii STATEMENT OF INTEGRITY I hereby declare having conducted this academic work with integrity. I confirm that I have not used plagiarism or any form of undue use of information or falsification of results along the process leading to its elaboration. I further declare that I have fully acknowledged the Code of Ethical Conduct of the University of Minho. ABSTRACT Nowadays, with the development of bigger and more complex applications, the architectural paradigm for application development is changing from a more traditional Monolithic approach to an architectural style called Microservices. In this more recent, and increasingly popular, style of developing applications, a tool that has also become increasingly more popular is API Gateways. In this thesis I explored these and a few other concepts on various examples, recording my experience, with the intent to create a guide on how to more efficiently implement these tools on to your own projects, facilitating the usually long and arduous process of researching, learning, and implementing new technologies into your work. Keywords: Microservices, API Gateway iii RESUMO Hoje em dia, com o desenvolvimento de aplicações maiores e mais complexas, o paradigma arquitetural para desenvolvimento de aplicações está a transacionar do estilo Monolítico tradicional para um estilo de arquitetura chamado Microserviços. Neste mais moderno, e cada vez mais popular, estilo de desenvolvimento de aplicações, uma ferramenta que também se tem tornado cada vez mais popular tem o nome de API Gateway. Nesta tese eu explorei estes e outros conceitos em vários exemplos, documentando a minha experiência, com a intenção de criar um guia em como o leitor pode mais eficientemente implementar estas ferramentas nos seus próprios projectos, facilitando o normalmente longo e trabalhoso processo de pesquisa, aprendizagem, e implementação de novas tecnologias no próprio trabalho. Palavras-Chave: Microserviços, API Gateway iv CONTENTS 1 introduction 1 1.1Motivation 1 1.2Objectives 2 1.3Development Approach 2 1.4Document Structure 2 2 state of the art 3 2.1Microservices 3 2.2API Gateways 4 2.3Kong and other alternatives 6 2.3.1Kong 6 2.3.2Amazon API Gateway 6 2.3.3Apigee 6 2.3.4WSO2API Manager 6 2.3.5Kong vs alternatives 7 3 guide/development 8 3.1Introduction 8 3.2Microservices 8 3.3Docker 9 3.4Kong 11 3.5NGINX and the front-end development 14 3.6HTTPS 16 3.7Examples 18 3.7.1Equivalencias App 18 3.7.1.1Introduction to the app 18 3.7.1.2Docker 19 3.7.1.3Kong 24 3.7.1.4NGINX 25 3.7.1.5The Approach and Difficulties found 28 3.7.2Animals Wiki App 35 3.7.2.1Introduction to the app 35 3.7.2.2Docker 36 3.7.2.3Kong 41 3.7.2.4NGINX and HTTPS 43 3.7.2.5The Approach and Difficulties found 46 v contents vi 4 hypatiamat 57 4.1Introduction to the app 57 4.2Development of the Web application 58 4.2.1Hypatiamat Backoffice 58 4.2.2Kong and JWT tokens 61 4.2.3Login interface 64 4.3Outcome 73 5 conclusion 74 LIST OF FIGURES Figure 1Monolithic vs Microservices (Faria)4 Figure 2Microservices architecture with an API Gateway (api)5 Figure 3Docker-compose file example 9 Figure 4Context and Dockerfile 10 Figure 5Docker-compose front-end ports 11 Figure 6Docker-compose Kong 12 Figure 7kong.yml file 13 Figure 8Front-end Dockerfile 14 Figure 9nginx.conf 15 Figure 10 Front-end Dockerfile 16 Figure 11 nginx.conf with HTTPS 17 Figure 12 Request flow 25 Figure 13 Front-end Equivalencias App 29 Figure 14 Equivalencias Microservices Architecture 33 Figure 15 Equivalencias Request Flowchart 34 Figure 16 Request flow 43 Figure 17 Front-end Animals-Wiki App (same as Equivalencias App) 51 Figure 18 Animals-Wiki Microservices Architecture 55 Figure 19 Animals-Wiki Request Flowchart 56 Figure 20 Old vs New - token storage 60 Figure 21 Main Menu 67 Figure 22 Register Menu 68 Figure 23 Backoffice login Menu 69 Figure 24 TPC login Menu 70 Figure 25 Backoffice App 71 Figure 26 TPC App 71 Figure 27 Hypatiamat Architecture 72 Figure 28 User experience flowchart 73 vii 2.3. Kong and other alternatives 6 2.3 kong and other alternatives Kong API Gateway is not the only possible choice when it comes to managing APIs. A few of the most popular alternatives are: Amazon API Gateway,Apigee and WSO2API Manager. (There are many more alternatives and which is best is subjective but for the purposes of this thesis I will talk about these in specific). 2.3.1Kong Kong is an API Management tool that became open-source in 2015. It is widely used by developers all over the world and is a great choice for anyone looking for a free API Gateway tool. It runs on Lua and supports plugins like rate-limiting, authentication, load-balancing, and many others. It also has an enterprise version. (Faren) 2.3.2Amazon API Gateway AWS API Gateway (or Amazon API Gateway) is an API Management tool provided by Amazon. From their website - "Amazon API Gateway is an AWS service for creating, publishing, maintaining, monitoring, and securing REST, HTTP, and WebSocket APIs at any scale. API developers can create APIs that access AWS or other web services, as well as data stored in the AWS Cloud." (AWS). The service is paid (per API call) but a free 12 month trial is available. 2.3.3Apigee "Apigee Edge, the self-service API management platform, enables companies to secure, scale, manage, and analyze their digital business, and grow API programs to meet the increase in demand. Edge enables enterprises to design and build the APIs that securely share their services and data." (Apigee) Apigee is a pay-per-API call solution that is mostly used by large companies. 2.3.4WSO2API Manager WSO2API Manager was initially released in 2012, and is a completely open-source and free tool for API management. It has security functionalities with it’s WSO2Identity Server, analytics tools with the WSO2Data Analytics Server and "workflow management capabilities with human interaction features with WSO2Business Process Server" (Gunaratne) 2.3. Kong and other alternatives 7 2.3.5Kong vs alternatives All of these solutions are great and are definitely reasonable choices for the purposes of this thesis, but Kong does stand out from the others by being a free alternative with intuitive use and excellent plugin support. It’s for those reasons that Kong was chosen for the API Manager role in this dissertation. 3 GUIDE/DEVELOPMENT Learning new technologies when starting new projects can be quite a difficult task. It involves a lot of research, reading documentation, testing, debugging, etc. Thus, a guide that focuses on explaining how these technologies work in a technical and practical way, with a few case studies as examples, might prove to be helpful to someone who never used said technologies. This thesis is an attempt at creating that guide. 3.1 introduction This section is composed by a guide to a Microservices architecture followed by a detailed accounting of the experience gained with several web applications, the process of transforming them into the Microservices architecture and the problems faced. The guide was constructed along the writing of this thesis and was made with the purpose of assisting those who hope to transform or make web applications that run on a Microservices architecture and API Gateway. It is a generalization of the many areas you can address the matter (from how Microservices work to the set up of the API Gateway) and, as said above, it will end with a couple of examples of web apps, used as case studies, to transform them into the Microservices architecture assisted by API Gateway Tools. 3.2 microservices Before trying to apply an API Gateway in your project, it makes sense to make sure you have a Microservices Architecture. This is because an API Gateway is a way to manage the communication and data transferring between different services, so having your application divided into different services is not only crucial, but almost necessary (if you intend to make the most out of an API Gateway like Kong). To do this, take your app and try to list the many different sectors of functionalities it has and run each of them in a different service. Using a popular example, a website where you buy clothes could have a service dedicated for the commenting system, one to list the available clothes, and one for a rating system. 8 3.3. Docker 9 It could even use external APIs, for example, an API to handle the money transactions performed in buying the clothes themselves. But, it is also important to not divide your app into too many services, as it could make your service network too complex. As a good rule of thumb, if you have two services that only communicate with each other and are performing simple tasks that could be done by only one service, it might be worthwhile to join those two services into only one. It is also useful (but not necessary) to separate your front-end from your back-end services. 3.3 docker When deploying an application on a machine it is incredibly useful to use Docker, this is because Docker creates containers, independent from the machine and OS (Operating System) it runs on, equipped with only the necessary software to fulfill its purpose, which is specified by the developer. This makes it possible for any application to run on any machine. Therefore, it is important to run every service in your application in its own container. Here is an example of a docker-compose file: Figure 3: Docker-compose file example 3.3. Docker 10 The docker-compose file is a config file which dictates what containers will be run when running the command docker-compose up and how they will run. In this example there are three containers that will be run: a front-end container (front-end-animals) which a user can communicate with through his/her browser, a back-end container (auth) which handles authorization, and a database container (mongo-users) which will store the users. Going through each container, starting with mongo-users, this container uses an image of MongoDB, a document-oriented NoSQL database. An image is the software in each you will be basing your container. The application that is deployed with this docker-compose file uses a MongoDB database so naturally the image for this particular container will be mongo. This container is also using something called volumes which, in short, allow for data persistence in a container, even if it goes down and has to be restarted. Because of how Docker works, when, for whatever reason, Docker fails and has to restart its containers, the data stored while it was running is lost. This because when the container fails and shuts down, the container no longer exists and the data created while it was running does not persist, even if it restarts automatically because it will start as a fresh instance of the container. To combat this we use Docker volumes. Docker volumes create a connection between the containers virtual file system and the hosts file system, so when data is written in the container it is also written in the hosts file system, and vice-versa, therefore making it so when a container is started with a fresh instance of the container, it automatically gets populated with the data it had from the hosts file system, thus having data persistence. The way volumes can be set up in a docker-compose file is like this: 1− host_path : container_path Meaning before the colon you have the path to the folder in your host machines file system, and after the colon you have the path in your containers virtual file system. The next container would be auth. In this container it is worth noting the "build" segment. Context indicates the path for the folder in which the rest of the "building" settings will be in relation to. Dockerfile indicates the path to the Dockerfile. Figure 4: Context and Dockerfile 3.4. Kong 11 The Dockerfile is another file used in building the container, besides the docker-compose.yml file. From the official Docker documentation "Docker can build images automatically by reading the instructions from a Dockerfile. A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image." meaning it allows us developers to build our containers with even more detail, facilitating the whole process of deploying an application. Lastly, in front-end-animals it is worth mentioning the "ports" segment. This defines what port to expose our container to in our machine. Since users will only be directly communicating with the front-end container through the browser, this is the only container the needs to expose ports. In this case, since the application is running on port 443 inside the container, and on the client side we want to be able to connect to the application through port 12090, ports were configured this way. Figure 5: Docker-compose front-end ports It is also worth mentioning that in all containers the "restart: always" setting was enabled, which makes sure whenever a container goes down for any reason it immediately restarts making sure there are essentially no down-times. 3.4 kong Kong is the API Gateway that will be showcased in this guide, but any API Gateway works and they almost all of them work essentially on the same principles. Kong can be deployed in many different ways, but because we already have Docker running it makes sense to use Docker to deploy Kong as well. When deploying with Docker, you also have the choice to run Kong with two modes: with a Database or without a Database (DB-less mode). These choices are up to you, the developer, and you can and should look at the documentation when setting up Kong (Documentation). In this guide, we will be going with DB-less mode. To deploy Kong this way, we will need to set up two documents: the docker-compose file, which we already have and will be adding Kong on to it, and a kong.yml config file, with the configuration for Kong. 3.4. Kong 12 Figure 6: Docker-compose Kong There is not much need to change this but the documentation elaborates on why it is set up this way. But it is worth noting that because we are running Kong inside a container, Kong’s configuration file must also be inside the container. We could go about this in two ways: copying the file over to the container, or mapping the config file which is the host’s file system onto the config file created in the container’s file system, through volumes. In this case, its the latter. (Also, the kong.yml file has to be on the same folder that the docker-compose file is, because of how the volume is set up) 3.4. Kong 13 Figure 7: kong.yml file This is configuration for a basic kong.yml file. It lists the services, which each have a name (up to the developer) , a URL to the service (in this case the Kong container can communicate with the other two containers through those URLs, but these don’t have to be other containers, they can lead to external APIs if you wish), and routes, which also have a name and a path. This path is what our front-end will use to communicate with the other services through Kong. For example, when attempting to communicate with the Animals API, instead of communicating directly through http://api:7777, our front-end will communicate through http://kong:8000/animals-api. In this configuration file there is also plugins, which is a big benefit of Kong because it has a huge library of plugins to choose from (Plugins). In this case, we are using the plugin "Key Authentication", which has the name "key-auth" (this name is NOT up to the developer, it depends on the plugin), and are applying it on a specific service, but you can also apply it to a specific route or apply it globally. 3.5. NGINX and the front-end development 14 3.5 nginx and the front-end development From the NGINX website "NGINX is an open source software for web serving, reverse proxying, caching, load balancing, media streaming, and more." (NGINX-Website). It is not obligatory but is definitely very useful in the building and deploying of any web application. To run your front-end container with NGINX you need two documents: • A Dockerfile (like previously discussed, it allows us to specify how we want our container to be built); • A config file (nginx.conf) Figure 8: Front-end Dockerfile The first half of the Dockerfile, the build stage, is just setting up the server as normal, first getting Node.js, then installing dependencies and finally running the server. (It is important to run it as a build for NGINX to work) On the other hand, the second half is setting up NGINX. First it gets NGINX in productionstage mode and then removes the existing default configuration. Then it copies some files, including the next file we will be addressing, the nginx.conf file, which is our custom configuration file. The last two "COPY" lines can be ignored for now, as they are for setting up a HTTPS server (the EXPOSE 443 line is also for HTTPS, here you can write EXPOSE 80, which is the normal port used in an NGINX server). Finally, it runs NGINX. 3.5. NGINX and the front-end development 15 Figure 9: nginx.conf A NGINX config file is bigger than this, but the default values are fine, the server block is where you want to change things. Firstly, the listen 80 line means that the web application will be run in port 80, meaning you can connect to it omitting the port number (example: instead of connecting to http://website:80 you can connect to http://website). The root block is fine as is. The first location block is saying if you go to http://website/ you will just go to the website itself, which is what you normally want. On the other hand, the next location block is saying that if you send a request to http://website/kong, that request will be routed to http://kong:8000. In these location blocks is where you would normally establish communication with other services, but, as we are using Kong, having those last two location blocks is enough, as our front-end will never communicate directly with other services, only with Kong. You may also note the "rewrite" line inside the location blocks. That makes it so our request doesn’t send the "/kong/" part in a request like "/kong/animals-api", only the "/animals-api" part, as that is what Kong is expecting for on its side. 3.7. Examples 22 auth This section of the docker-compose file, similarly to the previous container, is only instructing Docker to build this container after mongo-equi is built and also declares the path to the Dockerfile which is inside the "auth" folder. Here is the Dockerfile: 1 #Image 3FROM node : 1 5 5#Create folder WORKDIR /auth 7 #Copy app and i n s t a l l packages 9COPY package . json /auth/ COPY package−lock . json /auth/ 11 RUN npm i n s t a l l COPY . /auth/ 13 #Expose port 15 EXPOSE 9000 17 #Run app CMD [ "npm" , " s t a r t " ] This Dockerfile works the exact same way as the previous container, which makes sense as it is also a server running on Express. 3.7. Examples 23 interface-auth Once again, this container works in a similar way to the previous containers in the way that the docker-compose file is only instructing Docker of the following: the port to which app will be exposed to, the order in which to built this container, and where the Dockerfile is located. However, this time the Dockerfile is different to the previous containers’ Dockerfiles: 1 # build stage 3FROM node : lts −alpine as build −stage WORKDIR /front −end 5COPY package *. json /front −end/ RUN npm i n s t a l l 7COPY . /front −end/ RUN npm run build 9 # production stage 11 FROM nginx : stable −alpine as production −stage RUN rm /etc/nginx/nginx . conf /etc/nginx/conf . d/default . conf 13 COPY −−from=build −stage /front −end/d i s t /usr/share/nginx/html COPY ./ nginx . conf /etc/nginx/ 15 EXPOSE 80 CMD [ " nginx " , "−g" , "daemon off ; " ] The first half of this Dockerfile works like the other Dockerfiles, getting the image for node, copying the app and installing packages and then running it. However, this particular front-end will also be run using NGINX, so in the second half the following happens: • The image for NGINX is pulled; • The default configuration is removed; • The app is copied from the build stage; • The custom NGINX configuration is copied over (this particular file will be covered in a later section); • The port is exposed; • NGINX is run. Finally, it is worth noting that in all of the containers the option "restart: always" is enabled, which, as previously mentioned, makes it so in case the container shuts down for any reason it will restart automatically, avoiding down-times. 3.7. Examples 24 3.7.1.3Kong As previously stated, Kong’s job in this particular app’s architecture is not only to act as a reverse proxy between the authentication interface and it’s back-end, but also to try and manage, in some capacity, part of the authentication process itself, by providing a unique key to the client (which then saves that key in his/her cookies) and then checking if the user is in the possession of said key. If the user does not have the key that means he/she tried to bypass the authentication process. To this end, the following configuration was implemented for Kong: 1_format_version : " 2.1" 3servi c e s : <−−−−− − name: auth_service 5url : http : //auth :9000 routes : 7− name : auth−route paths : 9− /auth 11 consumers : <−−−−− 13 − username : user1 keyauth_credentials : <−−−−− 15 − consumer : user1 Here exactly two things are happening: • Aservice was defined, meaning that to reach http://auth:9000 (the authentication back-end container) one can use the path "/auth" in conjunction with Kong’s url: http://kong:8000/auth • A"consumer" and his credentials were created. A consumer is what consumes the service, so adding it to the configuration allows Kong to identify the user, which would in turn make it possible so that by attaching plugins to said consumer Kong becomes able to control the user with said plugins, like more complex authentication or rate-limiting. In this case though, no plugins are being used, because the app is only looking for the generated key which is in the consumers credentials. After a successful login a request will be made to http://kong:8001/consumers/user1/key-auth (user1being the created consumer) which will return the consumer object with the key inside. 3.7. Examples 25 3.7.1.4NGINX NGINX is absolutely not necessary for the success of this app, but because it would be crucial in the development of the next app, it was used in this much more simple app so it later could be used much more naturally. Nevertheless, NGINX is also working as a reverse proxy, this time between the user’s machine and the front-end itself, making it so this is the actual flow of a request call: Figure 12: Request flow 3.7. Examples 26 Particularly in this web application, NGINX is redirecting all calls made to specific paths to the appropriate services, in this case Kong. This was achieved by modifying the NGINX config file - nginx.conf: 1user nginx ; worker_processes auto ; 3 error_log /var/log/nginx/error . log notice ; 5pid /var/run/nginx . pid ; 7 events { 9worker_connections 1024; } 11 13 http { include /e tc/nginx/mime. types ; 15 default_type ap plica tion/octet −stream ; 17 log_format main ' $remote_addr − $remote_user [ $time_local ] " $request " ' ' $statu s $body_bytes_sent " $ h ttp_re f e rer " ' 19 ' " $http_user_agent " " $http_x_forwarded_for " ' ; 21 access_log /var/log/nginx/access . log main ; 23 sendfil e on ; #tcp_nopush on; 25 keepalive_timeout 6 5; 27 #gzip on ; 29 include /e tc/nginx/conf . d/*. conf ; 31 server { 33 l i s t e n 80 ; 35 root /usr/share/nginx/html ; index index . html index . htm ; 37 loc a tion / { 39 root /usr/share/nginx/html ; t r y _ f i l e s $uri /index . html ; 41 } 43 3.7. Examples 27 45 loc a tion /kong { <−−−−− rewrite /kong / ( . *) /$1break ; 47 proxy_set_header X−Real −IP $remote_addr ; proxy_set_header X−Forwarded−For $proxy_add_x_forwarded_for ; 49 proxy_set_header X−NginX−Proxy true ; proxy_pass http ://kong : 8000; 51 proxy_set_header Host $http_host ; proxy_cache_bypass $http_upgrade ; 53 } 55 loc a tion /kong−auth { <−−−−− rewrite /kong−auth / ( . *) /$1break ; 57 proxy_set_header X−Real −IP $remote_addr ; proxy_set_header X−Forwarded−For $proxy_add_x_forwarded_for ; 59 proxy_set_header X−NginX−Proxy true ; proxy_pass http ://kong : 8001; 61 proxy_set_header Host $http_host ; proxy_cache_bypass $http_upgrade ; 63 } } 65 } This configuration file is quite similar to the default configuration for an NGINX server, however it does have a crucial difference: the last two location blocks. These two blocks are what redirects the calls made to those specific url paths: • /kong will redirect those calls to http://kong:8000, the actual kong service that acts as a reverse proxy. • /kong-auth will redirect those calls to http://kong:8001, which is the admin port for Kong, having many functionalities but in this case it is used to get the consumer’s credentials. 3.7. Examples 28 3.7.1.5The Approach and Difficulties found Having visited every part of what makes this web application function in a microservices environment, in this section we will discuss how the idea for the architecture was conceived, the process of implementing it and the difficulties found along the way. It was known when first experimenting with web applications in this thesis that the end result was a Microservices architecture, so the natural first step in the transformation of this web app was the Dockerization of the main app "equivalencias" so it becomes a service capable of running on any machine. At the same time, the other objective was introducing Kong into this network of services, so in addition to the main app the default configuration of Kong was added to the docker-compose file and a simple service was set up. However, at this point there were no services defined in the kong.yml file as there were no services that we could define in the kong.yml file (except maybe the main app but the reason that was not done will be discussed later in this thesis). After setting up these two services this was the docker-compose file. 1version : "3.7" services : 3kong : container_name : kong 5r e s t a r t : always image : kong : l a t e s t 7volumes : − ./ kong . yml :/ usr/ l o c a l /kong/ d ec l ar a t iv e /kong . yml 9environment : − KONG_DATABASE= o f f 11 − KONG_DECLARATIVE_CONFIG=/usr/ l o c a l /kong/ d e cl a ra t iv e /kong . yml − KONG_PROXY_ACCESS_LOG=/dev/stdout 13 − KONG_ADMIN_ACCESS_LOG=/dev/stdout − KONG_PROXY_ERROR_LOG=/dev/stderr 15 − KONG_ADMIN_ERROR_LOG=/dev/stderr − KONG_ADMIN_LISTEN= 0.0.0.0:8001 ,0.0.0.0:8 4 4 4 ssl 17 equi : container_name : equi 19 build : context : ./ app 21 dock e rfile : ./ Dockerfile r e s t a r t : always 23 link s : − kong 25 ports : − " 12091:3018 " 27 networks : default : 29 a l i a s e s : 3.7. Examples 29 − equivalencias Although the goal of this thesis was to see how Kong behaves in a Microservices architectural environment, one of the main goals for this particular experiment was to see if it was possible to have a separate, isolated, authentication service to the app itself, of which Kong would be used to make sure the user was authenticated for the main app itself. To this end, a web interface with Vue.js was created, which was based on another app, one that would also be used later in this thesis - Animals Wiki. The homepage for that app with a simple login form was then used as an authentication interface. Figure 13: Front-end Equivalencias App For the back-end, Express was used, a Node.js web application framework, to quickly set up a server that handled user authentication. To do this, a MongoDB database was set up, it was then connected to the back-end and then the back-end checked if the user existed and the password matched, and if both of those conditions were true it returned a code status 201 (meaning a successful login), and if not it returned a code 403 (meaning the credentials were incorrect). router . post ( '/login ' , function ( req , res ) { 2User . consultar ( req . body . username ) . then ( dados => { 4i f ( ! dados ) res . sta t us (403) . jsonp ( false) 3.7. Examples 30 else i f ( req . body . password != dados . password ) res . statu s ( 403) . jsonp ( false) 6else return res . s tatus ( 201) . jsonp ( true ) } ) 8. catch ( err => res . statu s ( 500) . jsonp ( { err : err } ) ) } ) After this, these two services were added to the docker-compose file to introduce them to the network. However, Kong still had to be used in the authentication process, so two tasks were defined: First, define a service for the back-end component, just so Kong would be used as a reverse proxy thus increasing the developer’s understanding of how the API Gateway works. Second, the consumer credentials would be used to provide a unique key to the user so that only in possession of said key they would be able to access to the main app. This is what the kong.yml file became: 1_format_version : " 2.1" 3services : − name : auth_service <−−−−− 5url : http : //auth :9000 routes : 7− name : auth−route paths : 9− /auth 11 consumers : <−−−−− − username : user1 13 keyauth_credentials : <−−−−− − consumer : user1 3.7. Examples 31 And this function handles the login on the front-end saving the unique key in a cookie: getkey : function ( ) { 2axios ( { method : ' post ' , 4url : '/kong/auth/users/login ' , data : { 6username : t h i s . username , password : t h i s . password 8} } ) 10 . then ( data => { i f ( data . data ) { 12 axios . get ( '/kong−auth/consumers/user1/key−auth ' ) 14 . then ( response => { −−−−−> Vue . $cookies . set ( " key " , response . data . data [ 0] . key , " 1d" ) 16 t h i s . $ro uter . push ( ' / ' ) } ) 18 } } ) 20 . catch ( err => console . log ( err ) ) After setting up the main app and the authentication service, a database system had to be set up for both storing the data that the main app uses, but also the users for the authentication system. Consequently, the configuration for MongoDB was added to the docker-compose file: mongo−equi : 2container_name : mongo−equi r e s t a r t : always 4environment : MONGO_INITDB_DATABASE: equivalencias 6image : mongo volumes : 8− ./mongo−volume :/ data/db − ./ bds/equivalencias . j s :/ docker −entrypoint −in itdb . d/mongo− i n i t . j s : ro However, it is worth nothing the last block of code regarding volumes. Volumes in Docker are used for data persistence. 3.7. Examples 38 Diving deeper into each container: kong Kong’s set-up is the default one that has been used up until now. auth This container is mainly built through the Dockerfile, but it is worth mentioning the links block because it is setting up the build so that this container will only start after mongo-users is up and running, as it expresses dependency between the services as well as links them. Going through the Dockerfile: #Base Image 2FROM node : 1 5 4#Create work directory WORKDIR /auth 6 #Copy the app and i n s t a l l dependencies 8COPY package . json /auth/ COPY package−lock . json /auth/ 10 RUN npm i n s t a l l COPY . /auth/ 12 #Expose port 14 EXPOSE 9000 16 # S t a r t the app CMD [ "npm" , " s t a r t " ] As is documented, here the app is being copied to the container, dependencies are being installed and finally the app is being run on the exposed port. api This container functions the exact same way as the previous one. Here is the Dockerfile: 1#Base Image FROM node : 1 5 3 #Create work directory 5WORKDIR /api 7#Copy the app and i n s t a l l dependencies COPY package . json /api/ 9COPY package−lock . json /api/ RUN npm i n s t a l l 3.7. Examples 39 11 COPY . /api/ 13 #Expose port EXPOSE 7777 15 # S t a r t the app 17 CMD [ "npm" , " s t a r t " ] mongo-users This is the default configuration for a MongoDB based container, with the name for the database being Animals-auth and a volume for data persistence being set up through - ./mongo–volume:/data/db graphdb GraphDB is not a very common choice for a database, so setting up this container was not very straightforward. Firstly, it is a graph oriented database which is already not the most popular type of database. Secondly, even between graph oriented databases GraphDB is not the top choice. This makes it so there might not be as much resources available online, like Docker support. There is an official Docker image for GraphDB provided by Ontotext on Dockerhub, but not for the free version of GraphDB. However, there is a Dockerfile for the free version on their Github, but this Dockerfile was not quite what was being looking for. Instead, Khaller’s image for GraphDB was used as it allowed for an easy way to initialize repositories. Thus, in the docker-compose file the image is being pulled from khaller/graphdbfree:9.10.0. Also, port 9200 is being exposed in the host machine from port 7200 in the container. This so the Workbench mode could be reached. However, the image was not enough as the repository would have to be set up and the existing data would have to be imported. Therefore, this Dockerfile was configured: 1FROM k hal ler/graphdb−fr e e : 9.1 0 .0 3ENV GDB_HEAP_SIZE=2G 5RUN mkdir −p /repository . i n i t /Animals 7RUN mkdir −p /temporary−folder 9COPY animals −complete . t t l /repository . i n i t /Animals/toLoad/animals −complete . t t l 11 COPY config . t t l /repository . i n i t /Animals/config . t t l 3.7. Examples 40 In here the heap size is being set to two gigabytes because the file with the animal data was so big the container would crash while trying to import it. Then, two folders are being created - repository.init is of special importance. According to the image documentation from khaller, this folder is where the repository initialization must happen. Inside the /repository.init/Animals folder the config file for the repository must be present, and also another folder called toLoad must be present with the Turtle file with all of the animal data inside. Hence, the last two lines. Lastly, looking inside the repository configuration file: 1# Configuration template for a GraphDB−SE repository # 3@prefix rdfs : <http : //www.w3. org/2000/01/rdf −schema# >. @prefix rep : <http : //www. openrdf . org/config/repository # >. 5@prefix sr : <http : //www. openrdf . org/config/repository/ s a i l # >. @prefix s a i l : <http : //www. openrdf . org/config/ s a i l # >. 7@prefix owlim : <http : //www. o nto te xt . com/ t r r e e /owlim# >. 9[ ] a rep : Repository ; rep : repositoryID " animals " ; <−−−−− 11 rdfs : l abel " Animals repo " ; <−−−−− rep : repositoryImpl [ 13 rep : repositoryType " graphdb : FreeSailRepository " ; sr : sailImpl [ 15 s a i l : sailType " graphdb : F reeSa i l " ; 17 # r ul e s e t to use owlim : rul e s e t " empty" ; 19 # disable context index ( because my data do not uses contexts ) 21 owlim : enable −context −index " f a l s e " ; 23 # indexes to speed up the read queries owlim : en ablePredica teList " true " ; 25 owlim : enable − l i t e r a l −index " true " ; owlim : in −memory− l i t e r a l −properties " true " ; 27 ] ] . This is a default configuration for a GraphDB repository, everything expect for the repositoryID and label, which define the id and name of the repository, respectively. 3.7. Examples 41 front-end-animals Lastly, the container for the front-end of the app. It is noteworthy to look at the links block as it is set up so front-end-animals will wait for every other container to be up and running before starting. The port is also being exposed to 12090 to the host machine from 443 in the container. It’s 443 because that is the default port for websites running on a HTTPS connection, contrary to HTTP servers which run on port 80. Going through the Dockerfile: # build stage 2FROM node : lts −alpine as build −stage WORKDIR /front −end 4COPY package *. json /front −end/ RUN npm i n s t a l l 6COPY . /front −end/ RUN npm run build 8 # production stage 10 FROM nginx : stable −alpine as production −stage RUN rm /etc/nginx/nginx . conf /etc/nginx/conf . d/default . conf 12 COPY −−from=build −stage /front −end/d i s t /usr/share/nginx/html COPY ./ nginx . conf /et c/nginx/ 14 COPY ./ c e r t s /_ _ep l_ di_ umi nh o_p t_c ert if ica te . ce r /e t c/ s s l / COPY ./ c e r t s /epl . di . key / etc/ s s l / 16 #EXPOSE 80 EXPOSE 443 18 CMD [ " nginx " , "−g" , "daemon off ; " ] The first half is as usual, installing the Vue.js app and running it. Although, in the second half NGINX is being set up. The details for this configuration will be explored further ahead but, aside from the two COPY ./certs/ lines which will also be explored further ahead in the HTTPS section, this configuration is default and the one used in the previously discussed app. 3.7.2.3Kong Kong in this web app functions, as usual, as a reverse proxy. But, contrary to the last app - equivalencias, this time it is being used to a bigger extent. Last time it only served as a sort of middle-point between the front-end and the back-end of the authentication service. This time however, it now deals with two services, the back-end of the authentication service and the back-end of the core app, the service that deals with the retrieval of the animal data. Furthermore, Kong will also use one of the plugins from its extensive library to build a "authentication wall" between the front-end and the back-end of the core app, so a user can only access that information if they are indeed authenticated. 3.7. Examples 42 To this end, the following configuration was implemented for Kong: _format_version : " 2.1" 2 services : 4− name : animals − se rv ic e <−−−−− url : http : //api :7777 6routes : − name : animals −route 8paths : − /animals −api 10 − name : auth_service <−−−−− url : http : //auth :9000 12 routes : − name : auth−route 14 paths : − /auth 16 plugins : 18 − name : key−auth <−−−−− ser vic e : animals −se rv ice 20 config : key_names : 22 − apikey key_in_body : true 24 key_in_query : true consumers : 26 − username : user1 keyauth_credentials : 28 − consumer : user1 As is customary, the services block details Kong’s services and, in this case, as was said, the services for the authentication back-end and core app back-end are present. These could be reached by accessing http://auth:9000 for the authentication back-end and http://api:7777 for the core app back-end. Instead however, they can now be reached through http://kong:8000/auth and http://kong:8000/animals-api respectively. Also, a new block can be observed: the plugins block. Here one has to define: • The id of the service, in this case the Key_Authentication plugin was used, which has the id key-auth; • The specific service it is targeting (it can also target an individual route or be applied globally to all services and routes); 3.7. Examples 43 • The configuration for the plugin. In this case, it was defined that the variable name for the key would be apikey and when sending a request the key must be either in the body or in the query. Lastly, exactly as it was in the previous app, there is a consumers and credentials block, which is necessary for a plugin like Key Authentication to work. 3.7.2.4NGINX and HTTPS As was said in this section on the equivalencias app, NGINX was crucial in the development of this app, this because it (or another server like Apache) is absolutely necessary if one intends to set up an HTTPS connection. Evidently, an HTTPS connection is in no way necessary for an app to function, but if the intent is for it to be used by anyone, getting a domain and hosting it on a server is a necessary step, as is protecting the connection between the client and the server with an HTTPS protocol. Nevertheless, NGINX still functions as the usual reverse proxy and so, the request call flow is still this: Figure 16: Request flow 3.7. Examples 44 Diving deeper into the NGINX configuration file - nginx.conf: user nginx ; 2worker_processes auto ; 4error_log /var/log/nginx/error . log notice ; pid /var/run/nginx . pid ; 6 8events { worker_connections 1024; 10 } 12 http { 14 include /e tc/nginx/mime. types ; default_type ap plica tion/octet −stream ; 16 log_format main ' $remote_addr − $remote_user [ $time_local ] " $request " ' 18 ' $statu s $body_bytes_sent " $ h ttp_re f e rer " ' ' " $http_user_agent " " $http_x_forwarded_for " ' ; 20 access_log /var/log/nginx/access . log main ; 22 sendfil e on ; 24 #tcp_nopush on; 26 keepalive_timeout 6 5; 28 #gzip on ; 30 include /e tc/nginx/conf . d/*. conf ; 32 server { # l i s t e n 8 0; 34 −−−−> l i s t e n 443 s s l ; 36 −−−−> s s l _ c e r t i f i c a t e /et c/ s sl /__epl_di_uminho_pt_certificate . cer ; −−−−> s s l _ c e r t i f i c a t e _ k e y /etc/ s s l /epl . di . key ; 38 −−−−> s sl_protocol s TLSv1TLSv1.1TLSv1.2; −−−−> ssl_ci p h e r s HIGH: ! aNULL : !MD5; 40 42 root /usr/share/nginx/html ; 44 index index . html index . htm ; 46 loc a tion / { 3.7. Examples 45 root /usr/share/nginx/html ; 48 t r y _ f i l e s $uri /index . html ; } 50 −−−−> locat ion ~ ^/\.well −known/acme−challenge /([ −_a−zA−Z0−9]+) $ { 52 default_type te x t /plain ; return 200 " $1. lnFOHBDi0bOZuZYejG−6m1It5J−xVCzsyL5X0yLJKIc " ; 54 } 56 loc a tion /kong { rewrite /kong / ( . *) /$1break ; 58 proxy_set_header X−Real −IP $remote_addr ; proxy_set_header X−Forwarded−For $proxy_add_x_forwarded_for ; 60 proxy_set_header X−NginX−Proxy true ; proxy_pass http ://kong : 8000; 62 proxy_set_header Host $http_host ; proxy_cache_bypass $http_upgrade ; 64 } 66 loc a tion /kong−auth { rewrite /kong−auth / ( . *) /$1break ; 68 proxy_set_header X−Real −IP $remote_addr ; proxy_set_header X−Forwarded−For $proxy_add_x_forwarded_for ; 70 proxy_set_header X−NginX−Proxy true ; proxy_pass http ://kong : 8001; 72 proxy_set_header Host $http_host ; proxy_cache_bypass $http_upgrade ; 74 } } 76 } As it was in the previous app, most of the configuration is the default configuration for an NGINX server, with the addition to the two location blocks: the /kong and /kong-auth location blocks. This time however, a few other lines of code or added for the set up of the HTTPS server: • The listen 80;line was commented and substituted by listen 443 ssl; as this is the customary port for a HTTPS connection; • The ssl_certificate,ssl_certificate_key,ssl_protocols and ssl_ciphers were added. These lines of code are part of a HTTPS NGINX default configuration and can be consulted here (NGINX_HTTPS), and, most importantly, the ssl_certificate and ssl_certificate_key define where the certificate and certificate key are located; 3.7. Examples 46 • The location ~^/\.well-known/acme-challenge/ block was added. In this app, to get HTTPS certificates Lets-Encrypt was used, and Let’s Encrypt uses something called an ACME challenge to figure out if we, the developer, are in control of the domain name we intend to host our server on. To do this, Let’s Encrypt provides the ACME client with a token and places a file on http://<YOUR_DOMAIN>/.well-known/acmechallenge/<TOKEN>. A validation will then start where Let’s Encrypt will try to retrieve this file and, if successful, the HTTPS connection will be established. So, to allow for this validation, this location block was added. This begs the question however, how to get a certificate from Let’s Encrypt. In this particular case, the website was being hosted on UMinho’s servers which already had certificates issued for *.epl.di.uminho.pt (the website is hosted on gate.epl.di.uminho.pt so this certificate was valid), but new certificates can easily be issued by using the Certbot ACME Client (Certbot) 3.7.2.5The Approach and Difficulties found Just like for the last app, in this section we will dive deeper into how the architecture was conceived, the development process and the problems that had to be overcome. The main goals this time, as previously said, were to take more advantage of Kong’s capabilities by using plugins and managing more services. So, like last time, the first step was the Dockerization of the app and, with the experience gained from the last app, this was mostly straightforward. As always, the default configuration for Kong was added to the dockercompose file as it is always the same, and a kong.yml file that could later be modified to take full advantage of Kong was also created. The configuration for the already existing app animals-wiki was also added, both the front-end and the back-end (at this point it only consisted of a menu that would take you to the list of animals): version : "3.7" 2services : kong : 4container_name : kong r e s t a r t : always 6image : kong : l a t e s t volumes : 8− ./ kong . yml :/ usr/ l o c a l /kong/ d ec l ar a t iv e /kong . yml environment : 10 − KONG_DATABASE= o f f − KONG_DECLARATIVE_CONFIG=/usr/ l o c a l /kong/ d e cl a ra t iv e /kong . yml 12 − KONG_PROXY_ACCESS_LOG=/dev/stdout − KONG_ADMIN_ACCESS_LOG=/dev/stdout 14 − KONG_PROXY_ERROR_LOG=/dev/stderr − KONG_ADMIN_ERROR_LOG=/dev/stderr 16 − KONG_ADMIN_LISTEN= 0.0.0.0:8001 ,0.0.0.0:8 4 4 4 ssl 3.7. Examples 47 api : 18 container_name : api build : 20 context : ./API dock e rfile : ./ Dockerfile 22 r e s t a r t : always networks : 24 default : a l i a s e s : 26 − front −end−animals front −end−animals : 28 container_name : front −end−animals r e s t a r t : always 30 build : context : ./ front −end/animals 32 dock e rfile : ./ Dockerfile ports : 34 − " 12090:80 " link s : 36 − kong − api 38 networks : default : 40 a l i a s e s : − auth As expected, the Dockerfiles are consistent as with every other configuration addressed in this thesis. This is the Back-end’s Dockerfile: 1#Base Image FROM node : 1 5 3 #Create folder 5WORKDIR /api 7#Copy app and i n s t a l l packages COPY package . json /api/ 9COPY package−lock . json /api/ RUN npm i n s t a l l 11 COPY . /api/ 13 #Expose port EXPOSE 7777 15 #Run app 17 CMD [ "npm" , " s t a r t " ] 3.7. Examples 54 However, contrary to the previous app, when the user gets to the animal listing, i.e. the core app, instead of manually checking with Kong if the key is correct, the requests are simply made with the key in the query, and if the user does not possess the key or the key is incorrect the app does not return the data and the user can not view the animal listing. 1handler(n) { l e t v = '& ' 3i f ( ! n ) v = ' ? ' −−−−−> axios . get ( '/kong/animals−api/animals ' + n + v + ' apikey= ' + Vue . $cookies . get ( " key " ) ) 5. then ( dados => { . . . 7} ) . catch ( err => console . log ( err ) ) 3.7. Examples 55 With all of these moving parts now working together, this became the definite version of the Microservices Architecture of this web app: Figure 18: Animals-Wiki Microservices Architecture 3.7. Examples 56 And this the flowchart of the user experience: Figure 19: Animals-Wiki Request Flowchart 4 HYPATIAMAT Hypatiamat is an education website dedicated to help students of all ages with Mathematics. It contains exercises, mini-games, resources on the curriculum and so much more that could potentially help the student. It is also a platform where a professor is capable of managing their classes, give out homework to their students, etc, and the student can complete their homework or compete in "tournaments", motivating the student to study. It is truly an all encompassing app that helps students and professors alike in the subject of Mathematics. Additionally, because it is composed of several different services, all of them isolated from each other, it became the perfect test to the developed architecture philosophy. 4.1 introduction to the app After experimenting with a few apps, doing a lot of research and recording the whole experience, it was finally time to tackle Hypatiamat. However, the architecture on which the app is built could be, in some ways, considered outdated and in need of a re-work. Because the Hypatiamat "app" is actually several different apps that students would need to log-in to individually and were isolated from one another, this website would actually be, as said above, the perfect app to take everything that was learned up until this point and test if it would work on a large app acting on an even larger scale. Specifically, two of the many apps this whole website is built upon, Hypatiamat Backoffice and Hypatiamat TPC would be transformed into a Microservices Architecture while Kong would be used to set up a general authentication system, avoiding the individual login per app problem just discussed. In this next section we will discuss: how the architecture was come up with, the process of implementing the idea for the app, the problems faced and the solutions that had to be come up with. 57 4.2. Development of the Web application 58 4.2 development of the web application As previously said, two services were tackled, Hypatiamat Backoffice and Hypatiamat TPC and the idea was to put them on a Microservices network and develop a separate, isolated and global Authentication service that allowed users to login to any app by only entering their credentials once. So, as the idea was to substitute the already established login systems the apps had, it was decided to first run these apps and see how that system worked, with the intention of making the fewest possible changes to these apps in this architecture transition. Thus, the first step was to run Hypatiamat Backoffice. 4.2.1Hypatiamat Backoffice First things first, a docker-compose file was created and added the already existing configuration from the Backoffice app to it: version : ' 3.0' 2 services : 4api −dados : build : 6context : ./ apiDados container_name : api −dados 8image : api : l a t e s t ports : 10 − " 3050:3050" inte r face −app : 12 build : context : ./ i n t e r f a c e 14 container_name : inte r face −app image : i n t e r f a c e : l a t e s t 16 depends_on : − " api −dados " 18 ports : − " 8080:8080" This file was going to be where the configuration for ALL services was but at that moment it only had Backoffice’s configuration because it was important to see how that specific app worked. Here are the Dockerfiles for the back-end (api-dados) and the front-end (interface-app) respectively: 1FROM node : alpine 4.2. Development of the Web application 59 3WORKDIR /app 5COPY package *. json ./ 7RUN npm i n s t a l l 9COPY . . 11 EXPOSE 9000 13 CMD [ "npm" , " s t a r t " ] 1FROM node : l t s −alpine 3WORKDIR /app 5COPY package *. json ./ 7RUN npm i n s t a l l 9COPY . . 11 EXPOSE 8080 13 CMD [ "npm" , " run " , " serve " ] This is the usual set-up we’ve been accustomed to, with the only difference being in the front-end’s Dockerfile as it does not use NGINX so those lines of code are not present. Before moving on, it is worth talking about WampServer. WampServer is a Windows software that allows users to create web applications with Apache, PHP and most importantly, aMySQL database. This is important because all of the existing data for the Backoffice and TPC app is in SQL files so importing that into WampServer’s MySQL database was a necessary step. Coming back to the Hypatiamat Backoffice app, with this Docker set-up the app was successfully ran but upon experimenting with the login system it was discovered a massive problem. The authentication worked with JWT tokens, and these tokens were being stored in LocalStorage. Now, when your app is running on a single domain this is no problem whatsoever, however, the authentication system works across multiple subdomains (or in this specific case across multiple ports as the whole app was run in localhost): one for the 4.2. Development of the Web application 60 login, one for the Backoffice app, and one for the TPC app. The problem is LocalStorage uses a same-origin policy which sandboxes its data, meaning if, for example, our token is on sub1.website.com and we go to sub2.website.com we can not access our token across the subdomains. There is a natural fix for this problem which is storing your JWT tokens on browser cookies, which can be accessed across multiple subdomains. Unfortunately though, this meant a refactoring of both Hypatiamat Backoffice and Hypatiamat TPC was needed to store its tokens in cookies. Thankfully, a solution that would make a re-write of the entire code for these apps not necessary was come up with. Instead of completely erasing the LocalStorage usage and its entire logic, we would keep that logic as is and change only the part where the app gets the token. In other words, instead of getting the token from LocalStorage, the app would search for it in the cookies (because that is where it would be stored in the login) and only then store it in the LocalStorage from the cookies and let the app check if the token is valid or not. Here is a graph that might help visualize the process: Figure 20: Old vs New - token storage After implementing this in the Backoffice app the same was done for the TPC app. 4.2. Development of the Web application 61 4.2.2Kong and JWT tokens When this point was reached, Kong was introduced into the mix and, because the app was using JWT tokens, the JWT plugin was opted for. This is the kong.yml file: 1_format_version : " 2.1" 3services : − name : backoffice −api 5url : http : //host . docker . i n t e rn a l :3050 routes : 7− name : bac ko ffice −api −route paths : 9− /backoffice −api − name : tpc −api 11 url : http : //host . docker . i n t e rn a l :3052 routes : 13 − name : tpc −api −route paths : 15 − /tpc −api 17 plugins : − name : jwt 19 ser vice : backoffice −api enabled : true 21 config : secret_is_base6 4 :false 23 run_on_preflight : true key_claim_name : kid 25 claims_to_verify : −exp 27 − name : jwt ser vice : tpc −api 29 enabled : true config : 31 secret_is_base6 4 :false run_on_preflight : true 33 key_claim_name : kid claims_to_verify : 35 −exp − name : cors 37 config : ori gins : 39 − " *" methods : 41 − GET − POST 4.2. Development of the Web application 62 43 − PUT − DELETE 45 headers : − Accept 47 − Accept−Version − Content −Length 49 − Content −MD5 − Content −Type 51 − Date − X−Auth−Token 53 − Authorization exposed_headers : 55 − X−Auth−Token credentials : true 57 max_age : 3600 preflight_con tinue : false 59 consumers : 61 − username : user123 63 jwt_s e c r ets : − consumer : user123 65 se c r e t : YOUR_SECRET Unpacking this config file one block at a time, first we have the services: here is where the Kong services were defined for the back-ends of the Backoffice app and the TPC app. Next, the plugins: here we have two instances of the JWT plugin, one for each back-end service, and the CORS plugin. In the JWT plugin block there are a few things happening: obviously the name is the name of the plugin and service is the targeted service. enabled just means the plugin is active and config contains a few options you might decide to enable depending on your application. In this case, namely key_claim_name and claims_to_verify are important: the second one defines what fields the plugin will check that are valid, in this case exp or, in other words, the expiration date, but the first one, key_claim_name, will define the name of the unique key that every token must be signed with to be valid. It works very similarly to the key in Key Authorization from the previous app, in the way that it tracks which consumer, or user, is associated with the token, so it can be verified. Another thing that the token must be signed with is the secret. This is obviously up to the developer and should not be shared. It can be defined in the last block of the kong.yml config file, jwt_secrets. 4.2. Development of the Web application 63 Here is the function that signs the tokens (this function would only be created later but it shows how the signing of the token works): 1const s e c r e t = YOUR_SECRET 3generateToken = async function ( user , time) { try { 5. . . const kid = await axios . get ( ' http :// host . docker . inte r n a l :8001/consumers/ user123/jwt ' ) ; 7const token = jwt . sign ( { user , kid : kid . data . data [ 0] . key } , secret , { algorithm : "HS256" , 9expiresIn : time , } ) 11 return token } catch ( err ) { 13 // Handle Error Here console . error ( err ) ; 15 } } Circling back to the plugins, the CORS plugin is only present because the kong requests were being made across sub-domains, so CORS policy errors were obviously encountered. Thankfully, Kong developed a plugin to help with that. When testing sending requests to the Backoffice app through Postman, an API platform capable of creating and sending complex API requests to any url as well as get a detailed response, the request call succeeded if a signed token was sent through the Bearer Authentication header. However, both the Backoffice app and the TPC app already had their API calls defined, so, to not refactor every single request the front-end makes to the back-end of these applications, the code was changed so when the app first obtains the token it sets it as the Bearer Authentication token globally: i f (Vue . $cookies . isKey ( " token " ) ) { 2l e t tokenTemp = Vue . $cookies . get ( " token " ) localS tor age . setItem ( " token " , tokenTemp ) 4axios . defaults . headers .common[ ' Authorization ' ] = ' Bearer '+ localS tor age . getItem ( ' token ' ) ; } 4.2. Development of the Web application 70 And here is the TPC login menu: Figure 24: TPC login Menu 4.2. Development of the Web application 71 Upon entering the Backoffice app this is what a user would see: Figure 25: Backoffice App Entering the TPC app this is what a user would see: Figure 26: TPC App 4.2. Development of the Web application 72 With the login interface done the app was now completely functional. This is the final version of the architecture: Figure 27: Hypatiamat Architecture 4.3. Outcome 73 And this is a flowchart of the user experience: Figure 28: User experience flowchart It is worth noting that the new authentication system is very scalable and if one wishes to add more apps to the system they would only need to add a button and a login form and the login should work right away, assuming the new app stores its tokens in the cookies. If not, a similar refactoring done to Backoffice and TPC would need to be done to that app as well. 4.3 outcome After undertaking these case studies it is possible to say that the changes made to the original apps definitely are beneficial the functionality of the app as a whole and the knowledge acquired in the process of implementing these changes most certainly helped in the understanding of Kong, Microservices Architectures and the logic of login systems, as well as several other technologies and paradigms addressed in the making of this thesis. 5 CONCLUSION With the completion of this thesis the main goal was achieved: constructing a guide that could help the reader applying some or all of the technologies talked about in their own work. A few other goals were also achieved, like creating a general login system for every and any frontend service in the application, as well as attaining a deep understanding of API Gateways, Microservices, HTTPS passport configuration and authentication token handling. To accomplish this, we experimented on several case studies, first two smaller apps to create familiarity with the technologies and later a real life case with a considerably bigger and more complex application called "Hypatiamat". Reflecting on the progress made, it is possible to assert that Kong as an API Gateway is definitely one of the better options, as it is free and has many features, such as a huge library of plugins that can be easily and seamlessly implemented into any project, and it is also possible to assert that in huge applications with many services Kong can certainly be a strong asset because it allows for a better management of the service-to-service communication. However, it is worth noting that in small applications it might not be worth it to have this extra step in communication because managing that communication tends do be quite simple, or even big applications it might not be worth it if the plugin functionality is not being used, as something like NGINX is also capable of managing the communication network as Kong does. In conclusion, Kong can most certainly be a huge help in many applications, but, as most things, it really depends on the app and its function in that app. In future iterations of the work done in the Hypatiamat application we could add more applications to the login system as it is done in a scalable way that could easily introduce similar apps to its communication network. We could also take more advantage of the plugin system because, as of the writing of this document, only the JWT plugin is being used. We could take advantage of a rate-limiting plugin or an analytics plugin to gather data on the website’s users. 74 BIBLIOGRAPHY What does an api gateway do? URL https://www.redhat.com/en/topics/api/ what-does-an-api-gateway-do. What is amazon api gateway? URL https://docs.aws.amazon.com/apigateway/latest/ developerguide/welcome.html. The api gateway pattern versus the direct client-to-microservice communication. URL https://docs.microsoft.com/en-us/dotnet/architecture/ microservices/architect-microservice-container-applications/ direct-client-to-microservice-communication-versus-the-api-gateway-pattern. Animals-Wiki. URL https://gate.epl.di.uminho.pt/. Apigee. Apigee reviews, rating and features 2022. URL https://www.peerspot.com/ products/apigee-reviews. AZ_Animals. URL https://a-z-animals.com/. ACME Certbot. URL https://letsencrypt.org/docs/client-options/. Kong’s CORS. URL https://docs.konghq.com/hub/kong-inc/cors/. Docker. URL https://www.docker.com/. Kong Documentation. URL https://docs.konghq.com/gateway/latest/. Express. URL https://expressjs.com/. Faren. Kong — the microservice api gateway. URL https://medium.com/@far3ns/ kong-the-microservice-api-gateway-526c4ca0cfa6. André Faria. Melhores livros sobre microservices (microserviços). URL https://blog. andrefaria.com/melhores-livros-sobre-microservices-microservicos. Keith D. Foote. A brief history of microservices - dataversity. URL https://www.dataversity. net/a-brief-history-of-microservices/#. GraphDB Dockerfile Github. URL https://github.com/Ontotext-AD/graphdb-docker. GraphDB. URL https://graphdb.ontotext.com/. 75 BIBLIOGRAPHY 76 Imesh Gunaratne. Wso2api manager in a nutshell. URL https://medium.com/scalable/ wso2-api-manager-in-a-nutshell-eaac20812f0c. Hypatiamat. Hypatiamat website. URL https://www.hypatiamat.com/. Official Docker image for GraphDB. URL https://hub.docker.com/r/ontotext/graphdb/. Kong’s JWT. URL https://docs.konghq.com/hub/kong-inc/jwt/. Kong’s Key_Authentication. URL https://docs.konghq.com/hub/kong-inc/key-auth/. GraphDB Khaller. URL https://hub.docker.com/r/khaller/graphdb-free. Lets-Encrypt. URL https://letsencrypt.org/. Lua. URL https://www.lua.org/. MongoDB. URL https://www.mongodb.com/. Joe Nemer. Advantages and disadvantages of microservices architecture. URL https://cloudacademy.com/blog/ microservices-architecture-challenge-advantage-drawback/. NGINX. URL https://www.nginx.com/. NGINX-Website. URL https://www.nginx.com/resources/glossary/nginx/. NGINX_HTTPS. URL http://nginx.org/en/docs/http/configuring_https_servers. html. Kong Plugins. URL https://docs.konghq.com/hub/. Postman. URL https://www.postman.com/. Syntax Turtle. URL https://en.wikipedia.org/wiki/Turtle_(syntax). WampServer. URL https://www.wampserver.com/en/. Docker WSL2. URL https://docs.docker.com/desktop/windows/wsl/.