<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[edataconsulting - Medium]]></title>
        <description><![CDATA[Technology solutions definition, design and implementation - Medium]]></description>
        <link>https://medium.com/edataconsulting?source=rss----17e3ee3b4447---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>edataconsulting - Medium</title>
            <link>https://medium.com/edataconsulting?source=rss----17e3ee3b4447---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 10:10:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/edataconsulting" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Recommendations to prevent PHP files disguised as PDFs from being uploaded to your forms]]></title>
            <link>https://medium.com/edataconsulting/recommendations-to-prevent-php-files-disguised-as-pdfs-from-being-uploaded-to-your-forms-a2b9d8e8f613?source=rss----17e3ee3b4447---4</link>
            <guid isPermaLink="false">https://medium.com/p/a2b9d8e8f613</guid>
            <dc:creator><![CDATA[David Delgado Déniz]]></dc:creator>
            <pubDate>Thu, 08 May 2025 11:14:19 GMT</pubDate>
            <atom:updated>2025-05-14T12:12:28.875Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y5zxx68oZVyOxGXmrpO50Q.png" /></figure><p><a href="https://medium.com/edataconsulting/magic-numbers-in-the-world-of-pentesting-e22c6da4a6d6">In our previous article on Magic Numbers</a>, we explained that in the world of cybersecurity, ethical hackers test applications to identify vulnerabilities before malicious attackers can exploit them. The goal isn’t to overcomplicate the process, but to ensure that “the bad guys” won’t gain access to our client’s infrastructure.</p><p>This time, I will share with you some recommendations on how to protect your forms with a document upload feature from attacks like the one we described using Magic Numbers. It’s important to stay one step ahead!</p><p>If you want to make sure that only the right format and size files will be uploaded, it’s essential to implement validation on both the frontend and backend. These measures will not only improve the user experience, but also reinforce the security of your system and, hence, prevent the upload of malicious or invalid content. Let’s take a look at the process:</p><p><strong>Frontend validation</strong></p><p>While not secure on its own, it improves user experience by limiting file selection to those with a “.pdf” extension. But it isn’t enough.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*pUINKeT_Yk1DAd8dnBc4Rg.png" /></figure><p><strong>Backend validation</strong></p><ul><li>File extension</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*WWrWRE6s6x9_wtNkArAb2w.png" /></figure><ul><li>Real MIME file type</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*tngn1VHA4k87ALaRs5P-2g.png" /></figure><ul><li>Content verification (Magic Numbers)</li></ul><p>Valid PDFs start with “%PDF-”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*BreDNlzA-I7dk45K6x5qig.png" /></figure><ul><li>Rename the uploaded file</li></ul><p>As developers, we assign a safe filename to prevent the uploaded file from being executed as PHP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*TV1lhIvB8CcDRJfjp0Z2Tw.png" /></figure><p><strong>Server configuration</strong></p><p>We need to ensure that the server doesn’t execute any files in the upload directory by placing a .htaccess file in the upload directory of the web server with the following content:</p><p>&lt;Files *&gt;</p><p>Deny from all</p><p>&lt;/Files&gt;</p><p>&lt;Files *.pdf&gt;</p><p>Allow from all</p><p>&lt;/Files&gt;</p><p>php_flag engine off</p><p><strong>Other security measures</strong></p><ul><li>Limit the size of the files that can be uploaded. For example:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*aOyZUqEv0SifpW09pW4VQA.png" /></figure><ul><li>Sanitize filenames by allowing only permitted characters:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*Jmrx_RWOs_CtI8BiRrfnwg.png" /></figure><p><strong>Remember:</strong></p><p>- Do not ever trust just the Frontend validation. A hacker with basic knowledge can manipulate the JavaScript code on his browser and dodge restrictions. That is the reason why <strong>Backend validation</strong> is essential to avoid the execution of corrupted files.</p><p>- Combine several validation techniques like extension, MIME type, magic numbers, server configuration, etc.</p><p>- Isolate the uploaded files in a restricted directory and do not allow uploaded files to be stored in a location where they could be executed as code.</p><p>If you follow these recommendations, you will significantly reduce the risks. Nevertheless, if you would rather leave it to professionals, feel free to reach out to our <a href="https://edataconsulting.com/">team</a>.</p><p>Article by David Delgado, translated by Aranzazu Rodríguez</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2b9d8e8f613" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edataconsulting/recommendations-to-prevent-php-files-disguised-as-pdfs-from-being-uploaded-to-your-forms-a2b9d8e8f613">Recommendations to prevent PHP files disguised as PDFs from being uploaded to your forms</a> was originally published in <a href="https://medium.com/edataconsulting">edataconsulting</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Magic Numbers” in the World of Pentesting]]></title>
            <link>https://medium.com/edataconsulting/magic-numbers-in-the-world-of-pentesting-e22c6da4a6d6?source=rss----17e3ee3b4447---4</link>
            <guid isPermaLink="false">https://medium.com/p/e22c6da4a6d6</guid>
            <category><![CDATA[the-magic-numbers]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[David Delgado Déniz]]></dc:creator>
            <pubDate>Thu, 08 May 2025 11:13:20 GMT</pubDate>
            <atom:updated>2025-05-14T12:11:48.267Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RGzpRwA5GqVp0i3Y7O4AYQ.png" /></figure><p>In the exciting world of pentesting, ethical hackers, also known as pentesters, often encounter challenges that require creativity and cleverness to overcome. One of these challenges is uploading files through web panels or forms with specific restrictions. In this article, we will explore the fascinating technique of “Magic Numbers” and how they can be used to bypass these limitations.</p><p><strong>What are Magic Numbers?</strong></p><p>Magic Numbers are sequences of bytes found at the beginning of a file that indicate the type. For example, a PDF file starts with ‘%PDF-’, while a JPEG file begins with ‘FF D8 FF’. These initial bytes help systems identify the file format without relying on the extension.</p><p><strong>The Challenge: uploading a PHP file as a PDF</strong></p><p>Let’s say we are conducting a web audit and we come across a form that allows file uploads but has one restriction: it only accepts PDF files. Our goal is to upload a PHP file to achieve remote command execution. How can we bypass this limitation?</p><p><strong>The Bypass</strong></p><p>There are several techniques to work around this problem, but one is particularly interesting because it involves manipulating the Content Type and Magic Numbers. Let’s dive into the process:</p><p><strong>1.</strong> <strong>Intercepting the request with Burp Suite</strong></p><p>Using Burp Suite, we can intercept the file upload request and modify the Content Type to ‘application/pdf’, which will make the server believe we are uploading a PDF file.</p><p><strong>2.</strong> <strong>Modifying the Magic Numbers</strong></p><p>In addition to changing the Content Type, we need to modify the first bytes of the PHP file to make it appear as a PDF file. In order to do this, we will use HexEdit, a tool that allows us to edit the bytes of a file. Here are the specific steps:</p><p>- Open the PHP file in HexEdit.</p><p>- Modify the first bytes to match the Magic Numbers of a PDF file (‘%PDF-’).</p><p><strong>Practical example</strong></p><p>Let’s say tha we have a PHP file named ‘exploit.php’. As explained before, we open it in HexEdit and change the first bytes to look like this:</p><p>‘’’</p><p>%PDF-1.4</p><p>&lt;?php</p><p>// PHP file content</p><p>?&gt;</p><p>‘’’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*SDADwlOH3xsu5pB3pqJjIQ.png" /></figure><p>This way, the server will interpret the file as a PDF, even though it actually contains executable PHP code.</p><p>This is a common technique among pentesters and is also part of the attack simulations we conduct at <strong>edataconsulting </strong>for our clients. However, in the wrong hands, it can also be used for malicious purposes. Keep an eye out!</p><p>It is crucial that these practices are always used ethically and within the legal framework. Therefore, obtaining the proper authorization and ensuring compliance with current security and privacy regulations is essential before implementing them.</p><p>Last but not least, if you want to protect your systems from this type of attack and prevent unauthorized file uploads through file type spoofing, <a href="https://medium.com/edataconsulting/recommendations-to-prevent-php-files-disguised-as-pdfs-from-being-uploaded-to-your-forms-a2b9d8e8f613">check out our next article on security recommendations</a>.</p><p>Article by David Delgado, translated by Aranzazu Rodríguez</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e22c6da4a6d6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edataconsulting/magic-numbers-in-the-world-of-pentesting-e22c6da4a6d6">“Magic Numbers” in the World of Pentesting</a> was originally published in <a href="https://medium.com/edataconsulting">edataconsulting</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to switch from Karma to Jest using Angular]]></title>
            <link>https://medium.com/edataconsulting/how-to-switch-from-karma-to-jest-using-angular-7335588ffdf0?source=rss----17e3ee3b4447---4</link>
            <guid isPermaLink="false">https://medium.com/p/7335588ffdf0</guid>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[karma]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Bruno Picolo]]></dc:creator>
            <pubDate>Wed, 20 Dec 2023 09:06:21 GMT</pubDate>
            <atom:updated>2023-12-20T09:06:20.902Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KltbDZk45g_qs6pbdGMZvQ.jpeg" /></figure><p>Angular comes with Karma by default, but there are a lot of reasons to migrate Karma to Jest. Take a look to this <a href="https://charith-hettiarachchi.medium.com/why-use-jest-over-karma-for-angular-testing-b56ffa82f8#:~:text=Jest%20is%202%20to%203%20times%20faster%20than%20karma%20testing&amp;text=The%20tests%20that%20took%204,CI-CD%20will%20also%20reduce%2e">post</a>. Also, <a href="https://blog.angular.io/moving-angular-cli-to-jest-and-web-test-runner-ef85ef69ceca">Angular is interested in using Jest since v16</a>, so it’s better to get used to Jest 😁</p><p>This post is an easy guide to switch from Karma to Jest. As I know some of you might be short on time, I’ll get straight to the point. In the first part I will guide you with the easiest way to setup Jest (Angular v16 and higher). Then, in the second part, there is a similar guide using the older, but still used for Angular v15 and lower, way to migrate Karma to Jest. And finally, in the last part, I’ll explain how Angular 17 test configuration works in more detail.</p><p>Do you prefer to read code? Take a look to this <a href="https://github.com/diver-software/online-academy/commits/chore/setup-jest-with-angular-17/">Github repo branch</a>. You can follow commit by commit the process to migrate Karma to Jest.</p><p>Let’s go!</p><h3>From Karma to Jest using Angular Jest builder (Angular ≥ v16)</h3><p>As I mentioned, Angular is working to replace Karma with Jest to make Unit Testing easier. Since Angular v16 we can use an angular jest builder so the ng test command will configure and run jest.</p><h4>1. Uninstall unneeded deps</h4><p>npm uninstall karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter @types/jasmine</p><h4>2. Install Jest Dependencies</h4><p>npm install --save-dev jest @types/jest @angular-builders/jest</p><h4>3. Create the jest.confg.ts</h4><p>npx jest --init</p><p>Answers:</p><pre>The following questions will help Jest to create a suitable configuration for your project<br>✔ Would you like to use Jest when running &quot;test&quot; script in &quot;package.json&quot;? … yes<br>✔ Would you like to use Typescript for the configuration file? … yes<br>✔ Choose the test environment that will be used for testing › jsdom (browser-like)<br>✔ Do you want Jest to add coverage reports? … yes<br>✔ Which provider should be used to instrument code for coverage? › v8<br>✔ Automatically clear mock calls, instances, contexts and results before every test? … yes</pre><h4>4. Configure the builder adding the following to the angular.json</h4><pre>...<br>        },<br>        &quot;test&quot;: {<br>          &quot;builder&quot;: &quot;@angular-builders/jest:run&quot;,<br>          &quot;options&quot;: {<br>            &quot;configPath&quot;: &quot;./jest.config.ts&quot;<br>          }<br>        }<br>...</pre><h4>5. Use the Angular cli for testing</h4><p>Replace:</p><pre>&quot;test&quot;: &quot;ng test&quot;,</pre><p>With:</p><pre>&quot;test&quot;: &quot;ng test&quot;,<br>&quot;test:watch&quot;: &quot;ng test --watch&quot;</pre><h4>6. Running your tests</h4><p>To run all your tests, use the command npm run test. For interactive execution of tests, use npm run test:watch. This allows for a more dynamic testing experience.</p><h3>From Karma to Jest without Angular Jest Builder (Angular &lt; v16)</h3><p>This was the way to migrate from Karma to Jest before the angular Jest Builder.</p><h4>1. Uninstall unneeded deps</h4><p>npm uninstall karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter @types/jasmine</p><h4>2. Clean angular.json file</h4><p>Remove the test configuration (code extract below) from your angular.json.</p><pre>,<br>        &quot;test&quot;: {<br>          &quot;builder&quot;: &quot;@angular-devkit/build-angular:karma&quot;,<br>          &quot;options&quot;: {<br>            &quot;polyfills&quot;: [<br>              &quot;zone.js&quot;,<br>              &quot;zone.js/testing&quot;<br>            ],<br>            &quot;tsConfig&quot;: &quot;tsconfig.spec.json&quot;,<br>            &quot;inlineStyleLanguage&quot;: &quot;scss&quot;,<br>            &quot;assets&quot;: [<br>              &quot;src/favicon.ico&quot;,<br>              &quot;src/assets&quot;<br>            ],<br>            &quot;styles&quot;: [<br>              &quot;src/styles.scss&quot;<br>            ],<br>            &quot;scripts&quot;: []<br>          }<br>        }</pre><p>PS: do not forget the commas!</p><h4>3. Update test script</h4><p>Replace:</p><pre>&quot;test&quot;: &quot;ng test&quot;,</pre><p>With:</p><pre>&quot;test&quot;: &quot;jest&quot;,</pre><h4>4. Add jest dependencies</h4><p>npm i --save-dev jest @types/jest jest-preset-angular</p><h4>5. Create the setup-jest.ts</h4><pre>import &#39;jest-preset-angular/setup-jest&#39;;</pre><h4>6. Create the jest.confg.ts</h4><p>npx jest --init</p><p>Answers:</p><pre>The following questions will help Jest to create a suitable configuration for your project<br>✔ Would you like to use Jest when running &quot;test&quot; script in &quot;package.json&quot;? … yes<br>✔ Would you like to use Typescript for the configuration file? … yes<br>✔ Choose the test environment that will be used for testing › jsdom (browser-like)<br>✔ Do you want Jest to add coverage reports? … yes<br>✔ Which provider should be used to instrument code for coverage? › v8<br>✔ Automatically clear mock calls, instances, contexts and results before every test? … yes</pre><h4>7. Add jest-preset-angular</h4><p>Add the following to the jest.config.ts file:</p><pre>preset: &#39;jest-preset-angular&#39;,<br>setupFilesAfterEnv: [&#39;&lt;rootDir&gt;/setup-jest.ts&#39;],</pre><h4>8. Add the ts-node dependency</h4><p>npm install ts-node</p><h4>9. Configure the tsconfig.spec.ts</h4><p>Update/add the following properties to your tsconfig.spec.ts:</p><pre>&quot;types&quot;: [&quot;jest&quot;], // 1. Register Jest&#39;s tye defnition fils with the TS compiler<br>&quot;esModuleInterop&quot;: true, // 2. Avoids anoying warnings [check TS option](https://www.typescriptlang.org/tsconfig#esModuleInterop)<br>&quot;emitDecoratorMetadata&quot;: true // 3. Make Angular&#39;s dependency injection work with jest</pre><h4>10. Add test:watch script to package.json</h4><pre>&quot;scripts&quot;: {<br>  ...,<br>  &quot;test:watch&quot;: &quot;jest --watch&quot;<br>},</pre><h4>11. Running your tests</h4><p>To run all your tests, use the command npm run test. For interactive execution of tests, use npm run test:watch. This allows for a more dynamic testing experience.</p><h3>How does the Angular Test Configuration work?</h3><h4>Default Angular Test setup with Karma</h4><ol><li>npm run test: This command looks into the package.json file of your Angular project to find a script named test.</li><li>package.json Test Script: The default test script in an Angular project&#39;s package.json usually contains the ng test command.</li></ol><pre>&quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;ng test&quot;,<br>    // ... other scripts ...<br>}</pre><p>3. Angular CLI (ng test): The ng test command is a part of the Angular CLI. When executed, Angular CLI reads the project&#39;s angular.json file to find the test configuration.</p><p>4. Test Configuration in angular.json: The angular.json file contains configurations for various parts of your Angular application, including the test setup. This configuration specifies the Karma test builder and options for this builder.</p><pre>&quot;test&quot;: {<br>    &quot;builder&quot;: &quot;@angular-devkit/build-angular:karma&quot;,<br>    &quot;options&quot;: {<br>        // ... options like main test entry file, karma config file, etc. ...<br>    }<br>}</pre><p>5. Test Builder: Based on the configuration, the test builder Karma is invoked. Then:</p><ul><li>Starts a web server to serve the tests.</li><li>Looks for test entry points (typically src/test.ts) to load test files.</li><li>Executes the tests found in *.spec.ts files within a browser environment.</li><li>Reports the results of the tests.</li></ul><p>6. Webpack and test.ts: The test.ts file often uses Webpack&#39;s require.context to dynamically find and load all *.spec.ts files. This is part of the test execution process managed by Karma.</p><p>7. Running Tests and Reporting Results: Karma runs the tests in a browser and reports the results. This can be seen in the console or other configured reporters.</p><h4>Angular Test setup with Jest</h4><ol><li>npm run test: This command looks into the package.json file of your Angular project to find a script named test.</li><li>package.json Test Script: The default test script in an Angular project&#39;s package.json usually contains the ng test command.</li></ol><pre>&quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;jest&quot;,<br>    // ... other scripts ...<br>}</pre><p>3. Jest: The jest command takes over the role of finding the configurations and running the tests.</p><p>4. Jest Configuration: The <a href="https://jestjs.io/docs/configuration">Jest configuration</a>, typically jest.config.js, specifies where to look for test files. By default, Jest looks for files with specific naming patterns like *.spec.ts or *.test.ts.</p><p>We could configure Jest using JS, JSON or TS. Because TS has to be transpiled into JS we have to add <em>ts-node</em> as a dependency. Deciding which one to use depends on your project requirements and your personal preferences.</p><p>5. <a href="https://github.com/thymikee/jest-preset-angular#jest-preset-angular">jest-preset-angular</a>: The default setup to make Jest work with Angular easily.</p><p>To make use of jest-preset-angular, we have to instruct Jest to use it with the preset attribute in the jest.config. This will use a specific set of configurations optimised for Angular applications. Also, we have to apply the jest-preset-angular global configuration before the entire test suite. We apply the preset by referencing the setup-jest.ts in the setupFilesAfterEnv property at the jest.config.</p><p>The setup-jest.ts is not only used for applying the jest-preset-angular, it could also include global mocks configuration, setting up global variables, or performing initial setup tasks specific to your application&#39;s testing environment.</p><p>6. Running Tests and Reporting Results: Jest is already configured at this stage and will run the tests suite.</p><h4>Angular Test setup with Angular Jest Builder</h4><ol><li>npm run test: This command looks into the package.json file of your Angular project to find a script named test.</li><li>package.json Test Script: The default test script in an Angular project&#39;s package.json usually contains the ng test command.</li></ol><pre>&quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;ng test&quot;,<br>    // ... other scripts ...<br>}</pre><p>3. Angular CLI (ng test): The ng test command is a part of the Angular CLI. When executed, Angular CLI reads the project&#39;s angular.json file to find the test configuration.</p><p>4. Test Configuration in angular.json: The angular.json file contains configurations for various parts of your Angular application, including the test setup. This configuration specifies the Jest test builder and options for this builder.</p><pre>&quot;test&quot;: {<br>    &quot;builder&quot;: &quot;@angular-builders/jest&quot;,<br>    &quot;options&quot;: {<br>        // ... options like main test entry file, karma config file, etc. ...<br>    }<br>}</pre><p>5. Jest Test Builder: Based on the configuration, the test builder is invoked. Jest then:</p><ul><li>Configures Jest to work with Angular using angular-jest-preset</li><li>Executes the tests found in *.spec.ts files within a browser environment.</li><li>Reports the results of the tests.</li></ul><p>6. Running Tests and Reporting Results: Jest runs the tests in the terminal and reports the results.</p><p>The Angular Jest builder make the test configuration easier, we do not need anymore to take care about the jest-preset-angular. Also, because we are using an angular builder the steps are similar to other builders like Karma.</p><h3>Some Interesting metrics</h3><ul><li><a href="https://stackshare.io/stackups/jest-vs-karma-runner">Karma vs Jest pros and cons comparison</a>. It would be also great to have a Karma vs Jest performance review, but I haven’t found any. If you’re interested on performance, record your project performance running Karma follow these Karma to Jest migration steps and record Jest performance.</li><li><a href="https://npmtrends.com/jest-vs-karma">Karma vs Jest NPM trends</a>. This shows how Jest is more popular than Karma. It’s an interesting metric to deciding to switch to Jest because bugs will be solved faster and features will come faster as well.</li></ul><h3>Summary</h3><p>Angular testing is moving towards using Jest instead of Karma, and it’s important for us to update our projects to keep up with this change. In the first and second part of this article, we showed two easy ways to switch from Karma to Jest for Angular apps, the first one for Angular for newer Angular versions (&gt;v16) and the second for older versions. Then, in the last part, we compared how Angular works with both Karma and Jest. We also explained the purpose of different configuration files and their roles. This will give you a clearer understanding of how testing is done in Angular, making it easier for you to adapt to these changes.</p><p>We at <strong><em>edataconsulting</em></strong> regularly handle these software challenges. Take a look at our <a href="https://edataconsulting.es/">website</a> to know more about us.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7335588ffdf0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edataconsulting/how-to-switch-from-karma-to-jest-using-angular-7335588ffdf0">How to switch from Karma to Jest using Angular</a> was originally published in <a href="https://medium.com/edataconsulting">edataconsulting</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IaC for developers using AWS Copilot (part 2)]]></title>
            <link>https://medium.com/edataconsulting/iac-for-developers-using-aws-copilot-part-2-230f078b6f57?source=rss----17e3ee3b4447---4</link>
            <guid isPermaLink="false">https://medium.com/p/230f078b6f57</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws-copilot]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <dc:creator><![CDATA[Aridany Ruano Freire]]></dc:creator>
            <pubDate>Mon, 17 Jul 2023 08:52:45 GMT</pubDate>
            <atom:updated>2023-07-17T08:52:45.296Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g2uOoqnEbA7TCk93qwK1FQ.png" /></figure><p>This is the second (and last) part of a series of articles about AWS Copilot. <a href="https://medium.com/edataconsulting/iac-for-developers-using-aws-copilot-part-1-cae033a113ae">In the first one</a>, I talked about why we need a tool like this, and now we will see how Copilot works.</p><p>Let’s continue where we left off. Remember that, given a container-based application, and after two commands and a one-line edit in a descriptor file, we had this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yE4E7doVTP8jfDSy-j0UhA.png" /></figure><p>A highly available application listening in a public HTTP url.</p><h3>Anatomy of a copilot application</h3><p>Before going deeper into how copilot works, let’s stop to check three of the core concepts of copilot: <strong>Application</strong>, <strong>Service, </strong>and <strong>Environment</strong>.</p><ul><li><strong>Application</strong>. The concept of application can be understood as a group of services and environments that work together. Apart from this gluing of deployments, there is not many operations and attributes that work at an application level (create, delete, DNS configuration, not many more).</li><li><strong>Service. </strong>A service is a deployable container that is part of an application. The most important attribute of a service is its type. We’ve already used the Load Balanced Web Service in our first example, which translates into an internet-facing service with horizontal scaling. There are <a href="https://aws.github.io/copilot-cli/docs/concepts/services/#choosing-a-service-type">other types of services</a>, like services that listen to a message queue, that we’ll see later. There’s another related concept called <strong>Job</strong>, it’s like services but for batch processes. As far as you have a buildable docker project, release it as a service, and copilot will deal with all the deployment details (ECR, rollbacks in case of error, VPCs, subnets, scaling, balancing, etc.)</li><li><strong>Environment. </strong>An environment contains all the base resources needed to deploy our services (VPC, Subnet, ECS Cluster, Route53 configuration). We can create as many environments as we want. We can use them for a classic environment configuration (e.g. dev → uat → prod); or for ephemeral environments that are created and destroyed on demand.</li></ul><p>In one sentence, we can say that an AWS copilot <strong>application </strong>is a group of <strong>services </strong>that are deployed on <strong>environments.</strong></p><p>Now, let’s continue improving our simple example to show more Copilot features.</p><h3>Persistence</h3><p>If something is missing in our example, it’s a place to store data for our application. We can create a container-based database and deploy it as a copilot service, but we are on AWS, and given the array of possibilities that Amazon gives us, we shouldn’t need that. Copilot simplifies using AWS persistence services by allowing us to declare our interest in using them. So if we want to use an S3 bucket, we can go to the root of our service and run:</p><pre>copilot storage init -t S3</pre><p>It’ll ask us the bucket name (let’s say <em>our_bucket</em>), and next time we deploy our service (remember, just copilot deploy) the bucket will be there. How can we access it in our code? Copilot will inject an environment variable in our container named<em> OUR_BUCKET_NAME </em>containing the bucket name<em>.</em></p><p>At the time of writing, AWS Copilot’s storage command supports <strong>S3 </strong>buckets, <strong>DynamoDB </strong>tables, and <strong>Aurora Serverless</strong> clusters. If we need something different, we can create add-ons, and we will see them later.</p><p>There’s another persistence feature, <strong>EFS </strong>volumes, that doesn’t use the <em>storage</em> command. In this case, we declare them in the yaml descriptor. We could append to the end of the file:</p><pre>storage:<br>  volumes:<br>    myManagedEFSVolume:<br>      efs: true<br>      path: /var/efs<br>      read_only: false</pre><p>and after deployment we will have an EFS volume created, configured and mounted in the container. In my experience, to do this using just CloudFormation is quite a tedious piece of work.</p><h3>DNS and HTTPS Configuration</h3><p>In our example, the entry point to our application is the load balancer, and as we know, load balancers have not-so-friendly URLs. AWS Copilot can help us with this as long as we have a Route53 hosted zone that manages the domain that hosts the application.</p><p>To configure our application domain (and assuming that <em>my-app-domain.com</em> is managed by Route53), we must do this when we create the application:</p><pre>copilot app init --domain my-app-domain.com</pre><p>It’s a pity, but this implies that the domain must be known at application creation time, which might not always be the case. If we want to change it, or configure it, afterward, the only option is to delete the application and create it again.</p><p>Configured like this, every time we deploy a Load Balanced service to an environment, it will have a name like this: <em>service.environment.application.domain</em>. If we don’t like it, we can give a different name to a service by using the <em>alias</em> property in the manifest yaml file.</p><p>Also, at deploy time copilot manages the creation of an AWS Certificate Manager certificate and its configuration in the load balancer for HTTPS.</p><h3>Let’s add more services</h3><p>As it grows, we probably want to build our application as a set of services that work together.</p><h4>Asynchronous communication</h4><p>If services are not front-faced, then you’ll probably prefer to call them asynchronously. For this, copilot supports SQS and SNS and implements the <a href="https://docs.aws.amazon.com/sns/latest/dg/sns-common-scenarios.html#SNSFanoutScenario"><em>fan-out pattern</em></a><em>,</em> a great representation of the semantics of service asynchronous communication<em>.</em></p><p>Let’s use an example to see how to implement it in AWS autopilot. Suppose we have a system where anytime we create a new customer account, we have to send a communication to them. Also, let’s assume that we have a customer management service and a communications service that manages all our external communications using our new and shiny third-party service.</p><p>When a new customer is created in the customer management service, it will communicate this fact to the rest of the world by sending an SNS event, which is like saying</p><blockquote>Hey! to everyone interested, a new customer has been created, here you have the details</blockquote><p>The customer service will include this in its yaml descriptor:</p><pre>publish:<br>  topics:<br>    - name: new-customer</pre><p>and when we deploy it, we will have an SNS topic created (and its ARN injected as an environment variable in the container).</p><p>Anyone interested in this event will be subscribed to the SNS topic, including the communications service, which will use an SQS queue as the interface to receive calls. A queue semantics is a bit different than a topic, in this case, it will be like the communications service saying</p><blockquote>Hey! If anyone wants me to send a communication, please put a message in this queue, and I will do it as soon as I can.</blockquote><p>SQS queues allow for error processing, retries, etc. so they are a perfect match for services that can process their workload asynchronously from their callers.</p><p>For services that use SQS as its call mechanism, AWS autopilot has the <em>Worker </em>service type.</p><p>So the communications service will have a</p><pre>type: Worker Service</pre><p>in its definition. And also, the declaration of its queue and to which SNS topics it will listen.</p><pre>subscribe:<br>  topics:<br>    - name: new-customer<br>      service: customer<br>  queue:<br>    timeout: 300s<br>    dead_letter:<br>      tries: 3</pre><p>First, we say that this service queue will subscribe to the <em>new-customer </em>topic defined in the <em>customer </em>service. Then we declare the configuration for the SQS queue, in this case:</p><ul><li>messages will have a 5 minutes timeout before a retry</li><li>after three retries, messages will go to a dead letter queue*</li></ul><p><em>*dead letter queue creation included with copilot</em></p><h4>Internal services</h4><p>If you have services that need an HTTP interface but are internal to your system, then you can create a <em>Backend Service</em> that will be very similar to a <em>Load Balanced</em> one but with no internet-facing load balancer rules. They can be declared as:</p><pre>type: Backend Service</pre><h4>Batch Jobs</h4><p>AWS copilot also supports the need for scheduled recurrent jobs inside our application. Jobs are very similar in their definition and operation to Services. The only main differences would be in the descriptor:</p><pre> type: Scheduled Job<br><br>    on:<br>      schedule: &quot;@daily&quot;<br>    retries: 3<br>    timeout: 1h</pre><p>So, the type, the schedule (it could be a cron expression if we prefer), a timeout, and the number of retries for failure processing.</p><h4>Frontend application</h4><p>When we have a frontend javascript web application, deploying it as a container (with an nginx, express, etc. server embedded) could be overkill, especially with AWS having a great solution for this; the combination of S3 with Cloudfront. Fortunately, AWS copilot has recently introduced support for this pattern, which is a first, because it’s not a container-based solution, it could open the door to a whole new world for copilot.</p><p>Anyway, the example for this as it appears in the <a href="https://aws.github.io/copilot-cli/docs/manifest/static-site/">copilot documentation</a> is very self-explanatory:</p><pre>name: example<br>type: Static Site<br><br>http:<br>  alias: &#39;example.com&#39;<br><br>files:<br>  - source: src/someDirectory<br>    recursive: true<br>  - source: someFile.html</pre><p>Basically, we tell copilot where are the static resources it has to upload to S3, and we will have an extremely highly available web application published on the internet.</p><h3>What if I need a different AWS resource?</h3><p>It’s not an edge case that we would like to use an AWS resource not directly supported by AWS copilot (think documentDB, Elasticache, or OpenSearch, and those are just the first to come to my mind). We would like not to manage them by ourselves “outside” of the copilot services ecosystem. For this, we have addons.</p><p>Addons probably are my favorite feature of copilot. Thanks to them, it moves from being a good tool for quickly launching new products, to being the operational foundation of bigger systems, as it allows the integration of almost any resource that can be created with CloudFormation into our copilot environments.</p><p>Basically, an addon is a CloudFormation template written into the addons folder of our service repository. Anytime we deploy the service, the template will create or update the template’s stack for the environment we are deploying to. The trick here is that any value we declare in the template <em>Output </em>section will be injected as an environment variable in the container, if it is an IAM policy, the Task Role of our service will have it.</p><h3>The limitations</h3><p>Of course, AWS copilot is not perfect, and it has its limitations. Reflecting on them, I feel that most of those limitations come from the fact that copilot was, in the beginning, the cli tool for ECS, so now that it provides more than one would expect from such a tool, we, as users, want it to do things that are far from its original design guidelines.</p><h4>Addons, services and shared resources</h4><p>An addon is always owned by one service and not visible(in a copilot way, that is) from other services, and this is because addons cannot be services by themselves. They always have to be attached to a container.</p><p>Attach shared addons to existing services and use SSM Parameter Store or CloudFormation import as an intermediary, do work, but it’s not the ideal solution.</p><p>Another option that could be a solution, and doesn’t exist, is that of “common” or “shared” addons. Although I would prefer the notion of addons as services for most of my use cases, there are cases for shared addons, for example, IAM resources.</p><h4>Services are only containers (not anymore)</h4><p>There are cases where a different architecture could be more suitable than containers in Fargate. I’m thinking of using Lambda functions for Workers or Scheduled jobs when the 15-minute timeout limitation is not an issue.</p><p>Again, copilot is a tool for containers, but now that we have the static site type, The door’s open for including new types of deployments.</p><h3>To sum up</h3><p>We have seen how AWS Copilot is a powerful command-line tool that simplifies the development and deployment of containerized applications on AWS. Yes, like many other tools, it tries to follow the mantra “You can focus on your application logic and let us handle the underlying infrastructure and orchestration”. But what intrigues me, and I want to keep exploring, is that, unless most of them, it seems to find a sweet point between freedom and complexity while still enforcing good practices.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=230f078b6f57" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edataconsulting/iac-for-developers-using-aws-copilot-part-2-230f078b6f57">IaC for developers using AWS Copilot (part 2)</a> was originally published in <a href="https://medium.com/edataconsulting">edataconsulting</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IaC for developers using AWS Copilot (Part 1)]]></title>
            <link>https://medium.com/edataconsulting/iac-for-developers-using-aws-copilot-part-1-cae033a113ae?source=rss----17e3ee3b4447---4</link>
            <guid isPermaLink="false">https://medium.com/p/cae033a113ae</guid>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[aws-copilot]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Aridany Ruano Freire]]></dc:creator>
            <pubDate>Wed, 28 Dec 2022 09:25:01 GMT</pubDate>
            <atom:updated>2022-12-28T09:25:01.083Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yBfgmWQ0zMxzKjSSeMrS_w.png" /></figure><p>Development teams managing, in a self-service manner, the infrastructure platforms where their applications will run is one of DevOp’s main results.</p><p>The combination of Cloud Platforms and the concept of Infrastructure as Code (IaC) has provided us with the foundations to achieve this goal. But, tooling (and specially developer-oriented tools) are needed if we want teams to stop worrying and love the operational aspects of being the owners of their code.</p><p>In this pair of articles, I’m going to talk about the advantages that we, as developers, can get by using one of these tools: AWS Copilot.</p><p>In the first one, I will mostly rant about why we need a tool that simplifies and help us to enforce good practices. In the second one, we will go deeper into Copilot and see what we can get from it.</p><h3>Why a tool like this?</h3><p>Cloud computing services are great for developers, aren’t they? Before that, for apparently easy things such as getting a little more RAM for our applications, we had to request a specialized team that had to go through a bureaucratic cycle of tickets until someone, luckily, solved our need in a data center. Now, managing things like creating the environments where our applications will run can be done by ourselves, be it by API call or mouse click.</p><p>The same can be said about IaC.</p><p>Do you have a working testing environment and want to create a production replica (or the other way around) that is the same but some parameters? easily done using IaC.</p><p>Do you remember that tiny, urgent configuration fix we had to apply manually to the production environment to solve an issue that surged there and how we forgot to do it in staging? And how, two years later, it was incompatible with an update we did, so we went crazy because it broke production and we couldn’t replicate it in staging? That shouldn’t happen with IaC, as it makes easy to avoid applying manual changes to environments.</p><p>So many pains can be eased with IaC, including rollbacks, change version control, continuous integration, and even documenting your infrastructure.</p><p>But, very soon, we, developers, discovered that (surprise, surprise) making code run in production is more complex than doing it in our local environments. Sure, it’s easy to deploy our web application in AWS, be it in containers or not.</p><figure><img alt="Simple diagram of an instance in AWS" src="https://cdn-images-1.medium.com/max/920/1*J0XrmdmJrRNw2Xwie7w4lA.png" /></figure><p>But in production, we see that we have a much larger rate of requests, and we are expected to be 24/7 online. Thankfully, is not hard to make a cluster with our application in AWS, and anyway, we build our applications as stateless for nothing isn’t it?</p><figure><img alt="A simple diagram of a cluster of instances in AWS" src="https://cdn-images-1.medium.com/max/920/1*oDDYfvw0YWmbcU1qA6p-Hg.png" /></figure><p>Well, but now we need something in front of it to route all the requests, as we are not going to make all of our users learn the IPs of our servers, aren’t we? So we need a load balancer.</p><figure><img alt="A diagram of a cluster of instances with an Application Load Balancer in front" src="https://cdn-images-1.medium.com/max/920/1*r51YVNlfa4EQui4ztOebAg.png" /></figure><p>We are almost there, but not. This is better than instances IPs, yet we don’t want the application to be seen at whatevertheweirdname-2378461293.polar-north-2.elb.amazonaws.com. Therefore, we need DNS configuration with (potentially) Route53. Oh! and certainly, we want our app to be accessed by HTTPS, so AWS Certificate Manager is to the rescue.</p><figure><img alt="A more detailed diagram of an application in AWS using Route53 and Certificate Manager" src="https://cdn-images-1.medium.com/max/920/1*dIv7aHhkyvknuIm15m9KbQ.png" /></figure><p>These are the kind of things that we have to know and manage for the simplest of applications (I haven’t even gone into persistence). And you did think that those infrastructure and operation teams do nothing? those heroes deal with this stuff on a daily basis<a href="#fbd2">¹</a>.</p><p>And let’s be honest, developers don’t want to work with that level of detail day and night. Me, personally, I like it, and when I started to work with a devops style of development, I thought that it was something that all good developers should dominate. Now, I’ve learned how unfair was to try to impose the things I find enjoyable to others; the truth is that as much as I like IaC solutions like AWS Cloud Formation or Terraform, they are not the best tool for most developers. Being too low-level, they make things that are easy to think about (e.g. creating a web application that is available through the internet) a tedious process (for most developers) of obscure copy-pasting.</p><p>Just add a little bit more complexity to the solution, and it gets worse. I haven’t talked about security and networking (e.g. only the load balancer should be able to see the application instances). Or imagine that we built our application with some modularity, and now the load balancer has to route by path. Doing these with Cloud Formation, even I find boring<a href="#0828">²</a>.</p><p>It’s because of all of this that something that adds a level of abstraction is needed if we want development teams to be the owners of the code and not hate it, and of course, that development teams want to be the owners of the code, especially when the code is in its most critical stage, in production. If something fails there, who do you prefer to have the full access and knowledge to fix it? I, for one, vote for the people that built it over a team that only knows about where it’s deployed.</p><h3>What is Copilot?</h3><p>Copilot is a CLI tool to manage the lifecycle of container-based applications deployed in AWS. It is the replacement for the original ECS management command line tool, but it has evolved to be much more.</p><p>It simplifies the operation of our environments in AWS following and enforcing established good practices to create deployment platforms like the one we were starting to hint before.</p><p>So, an example to see how easy it is to start with it. We have a git repository containing a project that works in our local environment (like the simple web application in the previous section). The only prerequisite is that the application is containerized, so let’s assume we have a working Dockerfile in the repo.</p><p>Ok, now, after installing the copilot cli tool, we only have to type</p><p>copilot init</p><p>and copilot will ask you some simple questions</p><ol><li>Name of your app.</li><li>Type of service you are deploying. For our case, it would be Load Balanced Web Service. We’ll later see the other ones.</li><li>Name of the service. Our example is the most simple of cases, a single module, monolithic application, but of course, Copilot works great for modular multi-service applications.</li><li>Which is the docker file we want to use to deploy the application. When there is only one (as it probably should) it will default gracefully.</li><li>In which port inside your container do you want to send traffic to.</li></ol><p>And lastly, after setting things up, it will ask you if you want to deploy to a test environment, and after a couple of minutes, you will have an URL where you can connect to your application.</p><p>And what do we get? Something similar to one of the diagrams I showed before</p><figure><img alt="The architecture of a Copilot simple service" src="https://cdn-images-1.medium.com/max/880/1*RN1ARM5h3yCCgvGpjB9Ybw.png" /></figure><p>all running, all working, vpcs and security groups, ECS tasks and services, load balancer listeners and target groups.</p><p>As with many devops tools, copilot mixes an imperative approach, where, as we saw before, you command what you want to be done, with a declarative one, where you describe the desired state for your platform and then apply it. Copilot uses a YAML (nobody’s perfect) manifest. To find it, after creating the service with copilot init we can see a <em>copilot </em>folder in our repo root, inside that another one with the name we give to the service, and there we can see a manifest.yml.</p><pre># The manifest for the &quot;example&quot; service.<br># Read the full specification for the &quot;Load Balanced Web Service&quot; type at:<br>#  https://aws.github.io/copilot-cli/docs/manifest/lb-web-service/<br><br># Your service name will be used in naming your resources like log groups, <br># ECS services, etc.<br>name: example<br>type: Load Balanced Web Service<br><br># Configuration for your containers and service.<br>image:<br>  # Docker build arguments.<br>  build: Dockerfile<br>  # Port exposed through your container to route traffic to it.<br>  port: 8280<br><br>cpu: 256       # Number of CPU units for the task.<br>memory: 512    # Amount of memory in MiB used by the task.<br>count: 1       # Number of tasks that should be running in your service.<br>exec: true     # Enable running commands in your container.</pre><p>As you can see, it’s straightforward and down to the point, abstracting all the details behind the scenes; it just shows you the things you want to know and change. So if we want to create more instances of our application, it’s as easy as changing that <em>count</em> parameter to the number we want and run</p><p>copilot svc deploy</p><p>and that’s it, service scaled up.</p><figure><img alt="The architecture of a balanced copilot service" src="https://cdn-images-1.medium.com/max/1024/1*yE4E7doVTP8jfDSy-j0UhA.png" /></figure><p>And that’s all for the first chapter. In the next one, we will go deeper into AWS Copilot; and we will see how we can solve our real-life problems with it, showing both its strong points and its limitations. See you!</p><p>[1] <a href="#e163">^</a> And it gets worse, companies with several teams working independently, that is, the kind of companies we will deal with for most of our careers. We need some kind of governance there, some set of good practices that we want to apply to some extent, compliance requirements, cost managing etc. It is a daunting task to try to manage all of that without creating an independent, application-ignorant silo.</p><p>[2] <a href="#2ee8">^</a> My view now is that these low level platform knowledge should be for developers like regular expressions are for most. We know how they work and what they are used for, we remember just the basic stuff for the most simplest things, and we know where to look for help when the unusual feature that needs it arise. Forgetting all about it just a couple of days after we finished.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cae033a113ae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edataconsulting/iac-for-developers-using-aws-copilot-part-1-cae033a113ae">IaC for developers using AWS Copilot (Part 1)</a> was originally published in <a href="https://medium.com/edataconsulting">edataconsulting</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Java POI Report Generation]]></title>
            <link>https://medium.com/edataconsulting/automating-java-poi-report-generation-13bdffc4c0b5?source=rss----17e3ee3b4447---4</link>
            <guid isPermaLink="false">https://medium.com/p/13bdffc4c0b5</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[excel]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[report]]></category>
            <category><![CDATA[apache-poi]]></category>
            <dc:creator><![CDATA[Tiago Marques]]></dc:creator>
            <pubDate>Wed, 26 Oct 2022 08:05:36 GMT</pubDate>
            <atom:updated>2022-10-26T08:05:36.081Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dfDIeHVx-NGHw0ilC4sVAQ.png" /></figure><p>As programmers, we find many ways to write code to generate <em>Excel</em> reports. Usually, these solutions require tons of boilerplate code.</p><p>In this article, I present a routine created using <em>Java Reflection</em> to build <em>Java POI XLSX</em> reports using just a template and a data source. While other implementations like this exist (some even better), this is open source, so you don’t have to pay a cent to use it. Just learn or provide some constructive feedback.</p><p>Without further ado, let’s dive into it.</p><h3>The Excel Report Generator</h3><p>Created as a means to save time and effort when generating reports, the <em>Excel Report Generator</em> tool <em>(ERG)</em> is a simple <em>Java</em> class with <em>Java Reflection</em> routines designed to read an Excel template’s columns and comments and convert them into instructions to parse a database and feed data into it, thus generating the real report.</p><p>My motivation for creating this was to look at messy routines using low-level instructions to build reports, row by row and line by line. If we have a template, we can focus on how to retrieve the data and not on how to render the final result for the user.</p><p>This is how we go from template to real report:</p><ul><li>The template, an <em>Excel</em> file, contains <em>{placeholders}</em> that describes properties of <em>Java POJOs</em> that the <em>ERG</em> tries to access and replace with real content, as well as comments to describe more advanced methods to fetch data from the data-source (mainly lists iteration).</li><li>The first row and first column of the template has a special comment which indicates how many columns and rows the template contains in total. This helps <em>ERG</em> properly navigate through all the cells available in the template and process them accordingly.</li><li>Constant <em>[placeholders]</em> can be replaced with system information. At this moment, now there is only one available <em>[TODAY]</em> and, as the name suggests, it writes the current date and time.</li></ul><p>The comments can describe different ways to access lists within the <em>Java POJOs</em>:</p><ul><li>The <em>:page</em> comment is followed by two lines, representing the number of rows and columns respectively that each template comprises. It’s the only required comment that needs to be present for the <em>ERG</em> to properly process the template and generate the final report.</li><li>The <em>:for</em> comment is followed by three lines, the first one describes the <em>Java POJO’s</em> list property to iterate, and the second and third indicates how many rows and region it has respectively, which is the region that each iteration comprises.</li><li>The <em>:mergeBy</em> comment merges columns based on the length of the <em>Java POJO’s</em> list property indicated in the following line of the comment.</li><li>The <em>:iterateBy</em> comment is similar to the :for one, the only difference being that it does a horizontal iteration in a single row instead of a vertical one in a region.</li></ul><p>Placeholders can also contain pipes <em>{property|pipe}</em>. These indicate the type of information that the <em>Java POJO</em> property represents, and the types are described as follows:</p><ul><li>DATE: represents a <em>Date Java POJO</em> property. The written cell is of type <em>String</em>.</li><li>INTEGER: represents an <em>Integer Java POJO</em> property. The written cell is of type <em>Numeric</em>.</li><li>DECIMAL: represents a <em>Double/Float</em> <em>Java POJO</em> property. The written cell is of type <em>Numeric</em>.</li></ul><p>Finally, whenever a property is <em>null</em>, we can provide a standard label to be shown <em>{property?no data available|pipe}</em>, this gives a hint to the user that nothing was found to fill the report.</p><h3>A real use case scenario</h3><p>To showcase <em>ERG</em>, we’ll consider a scenario in which we want to generate reports for an Academic Application, with Students that attend Classes, which are lectured by Teachers, as shown in <em>figA</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GCzI3lgl5JGAWbATOFHq1g.png" /><figcaption>figA: Academic Application Entity Relationship Diagram</figcaption></figure><p>We want a report to display the records of each student, showing classes attended and which teacher lectured these classes, as sown in <em>figB.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*o3RDBWtScCX2opsHNM44cA.png" /><figcaption>figB: Report sample</figcaption></figure><p>First of all, we start by giving information about how many columns and how many rows we want in our template, by writing the <em>:page</em> comment in the first cell, as shown in <em>figC</em>.</p><pre>:page<br>9<br>5</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*e1voxgycYWJg9_EjvfF0WA.png" /><figcaption>figC: The :page comment</figcaption></figure><p>Later, we start to iterate through the Students list by adding the <em>:for</em> comment, as shown in <em>figD</em>, and specifying the properties of the Student class in each cell of the region defined. As shown in <em>figE</em>, the properties used are <em>name, birthDate, address, mobile, </em>and<em> email</em>.</p><pre>:for<br>students<br>6<br>4</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*rM1iO6GJkMAh5lo8AC0UMA.png" /><figcaption>figD: The :for comment for the Students</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*UeMXptO6tNpcCUTODHrl4Q.png" /><figcaption>figE: The properties of the Student</figcaption></figure><p>We also want to display each class attended by the Students, so we need to iterate within each Student list of Classes using again the <em>:for</em> comment, as shown in <em>figF</em>. As shown in <em>figG</em>, the properties used are: <em>name, averageGrade, </em>and<em> teacherName</em>. As the property <em>averageGrade</em> is a decimal, we need to use the <em>DECIMAL </em>pipe.</p><pre>:for<br>classes<br>2<br>2</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*XZ1JtYt9eKHaCoHTehxAUw.png" /><figcaption>figF: The :for comment for the Student classes</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*PWN5pCXeYRrmRQPOlYC_rg.png" /><figcaption>figG: The properties of the class</figcaption></figure><p>Finally, we want to display date information <em>[TODAY]</em> and give a name to the sheet <em>{title}</em>. The complete template is shown in <em>figH</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*QAw9MZM1JWpeN4vv-C4cDQ.png" /><figcaption>figH: The complete template</figcaption></figure><p>The code to process this template and generate the report follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00f957e3275eea5a5e432323828e3b3c/href">https://medium.com/media/00f957e3275eea5a5e432323828e3b3c/href</a></iframe><p>As can be seen in line 149, we provide a label for the <em>ERG</em> to show on the report whenever the given student’s list is empty. This situation is shown in <em>figI </em>(report filled with data) and <em>figJ </em>(empty report).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*UoEEuDLV85rNvLjPqfdlDw.png" /><figcaption>figI: Not empty list</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*z0vhIDE6LJJkMTRx3FmoeQ.png" /><figcaption>figJ: Empty list</figcaption></figure><h3>Another real use case scenario with :mergeBy and :iterateBy</h3><p>Now, let’s look at this report from a different perspective. Say that, of all available classes, we want to know which ones each student is attending and which ones he’s skipping, like in <em>figK</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CcoTqwjAG_XCiYNFNMEdWg.png" /><figcaption>figK: Report sample</figcaption></figure><p>To do this, we need to use two aforementioned special comments: <em>:mergeBy</em> will merge cells <em>G2, H2</em>, and <em>I2</em> into one with the title “Classes” and <em>:iterateBy</em> will describe which classes the student attended (marked with an <em>X</em>) and which ones he didn’t.</p><p>To do this, we need the list of classes to be accessible from the data-source class for the <em>:mergeBy</em> comment, like in <em>figL</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*RPAltrerTSjvIipHUrnwEA.png" /><figcaption>figK: mergeBy: comment for the data-source classes property</figcaption></figure><p>As in the first scenario, there’s a <em>:for</em> comment that iterates through the list of students, as shown in <em>figM</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*jILzw4cNyzTTQmtnds6BeQ.png" /><figcaption>figM: :for comment for the Student class</figcaption></figure><p>Let’s say that the mobile and e-mail information is optional for the student to provide, this means that their value can be null. In these cases, it’s interesting to be able to provide a label describing why we were unable to fetch the information, therefore, we use the optional parameter <em>? </em>for this purpose, as shown in<em> figN:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*rdfeMJ8VBmk_GIaEbsuTNQ.png" /><figcaption>figN: optional ? parameters</figcaption></figure><p>Finally, to get the list of classes names marked or not with an <em>X</em>, there’s a method on the Student class to cross-check the list of available classes with the attended ones:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d091207a04815cb1f6d83d0b94f3750a/href">https://medium.com/media/d091207a04815cb1f6d83d0b94f3750a/href</a></iframe><p>We use this method on the <em>:iterateBy</em> comment to draw the list of classes marked with <em>X</em>, like in <em>figO</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*Th9G1RPSplWi8bRp4L9wmg.png" /><figcaption>figO: the :iterateBy comment for the Student class</figcaption></figure><h3>Conclusion</h3><p>The <em>Excel Report Generator</em> provides an efficient way to handle and process excel reports in an automated way, discarding hundreds of hard-coded lines needed to generate reports. Developers are thus able to focus solely on how to retrieve the information (data-source) and not so much on how to display them in the report.</p><p>This is by no means the best project to get the job done, and there are many solutions out there, many of them paid. For sure, many flaws need to be fixed in the long run but this solution works well enough if you’re looking to automate your reports.</p><p>If you want to check <em>ERG, </em>you can go <a href="https://github.com/tiago-marques-nascimento/excel-report-generator">here</a><em>.</em></p><p>Thanks for reading! : )</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13bdffc4c0b5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edataconsulting/automating-java-poi-report-generation-13bdffc4c0b5">Automating Java POI Report Generation</a> was originally published in <a href="https://medium.com/edataconsulting">edataconsulting</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Typography tips for software developers]]></title>
            <link>https://medium.com/edataconsulting/typography-tips-for-software-developers-465696d285cb?source=rss----17e3ee3b4447---4</link>
            <guid isPermaLink="false">https://medium.com/p/465696d285cb</guid>
            <category><![CDATA[typographic]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-design]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[typography]]></category>
            <dc:creator><![CDATA[Yeray David Rodriguez Domínguez]]></dc:creator>
            <pubDate>Tue, 06 Sep 2022 12:16:27 GMT</pubDate>
            <atom:updated>2022-09-06T12:16:27.561Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hFLbHhrj41xfJVlCyTEmaw.png" /></figure><blockquote>Type is what meaning looks like</blockquote><blockquote><em>Max Phillips</em></blockquote><p>In the beginning, there was the HTML code. Whiteness was over the surface of the browser window, and some black characters hovering over it. And the web developer said, “Let there be CSS,” and there was color, shape, and size for the characters. The web developer saw that CSS was good, but that was because he wasn’t aware of all the implications linked to each one of the typography choices.</p><p>Because typography is not only about <em>fonts that look nice</em>. It’s about aesthetics, legibility, accessibility, and semantics. An only bad typographic choice may spoil all the work on a website, while a carefully planned typographic design will make it shine.</p><p>But, let’s settle some definitions first to establish a common soil:</p><p>According to Wikipedia, <em>Typography</em> is the art and technique of arranging type to make written language legible, readable, and appealing when displayed.</p><p>Some of the elements involved in the typographic design of a website are:</p><ul><li>Typefaces: font families, size, and weight of each glyph (character).</li><li>Color: of glyphs and also the background against which are rendered.</li><li>Leading: space between lines.</li><li>Tracking: uniformly adjust the space between all characters.</li><li>Alignment: usually left, right, justified, or centered.</li><li>Length (number of characters) of paragraphs lines</li></ul><p>Those elements correspond to specific CSS properties that have default values set by the user agent stylesheet, or a combination of them.</p><h3>Why developers must care about typography?</h3><p>Software developers create digital products that, in most cases, have a GUI (if we are creating an application) or content presentation (if we are crafting a corporate or informative website). In both cases, text will be used, that must be perfectly legible, accessible, pleasant to read, and coherent with the overall design.</p><p><em>“But in my corporation we have a designer that takes care of this kind of things”.</em> Well, congratulations, because not all developers have that privilege, and some of them have to take their own design-related decisions. And even having a designer, he probably won’t deal with CSS definitions and accessibility requirements. As front-end developers, we may not be responsible for specific design choices (although is advisable to at least know the reasoning behind those choices), but we do are for implementing them in a graceful and user-respectful way, and we need some typography knowledge to do it successfully.</p><h3>How to make good typography choices</h3><p>When the developer starts giving specific values to those properties to apply the desired design (that maybe doesn’t even exist, but emerges iteratively with trial-and-error), every decision (a change in the font family, make a text bigger, some color adjustment…) should comply with the following rules, sorted from more to less important:</p><ol><li>Legibility: the choice won’t reduce the general legibility of the text.</li><li>Accessibility: the choice won’t reduce the legibility of the text for specific users with some disability.</li><li>Coherency: the choice will preserve the semantic, functional, and aesthetic coherence of the text with the rest of the UI.</li><li>Aesthetic: the font won’t make the overall perception of the website unbalanced, unpleasant or annoying.</li></ol><p>It is not difficult to see what those rules are based upon: communication. Glyphs are the vessels used to send our message, and typographic choices may affect directly their capacity for fulfilling this goal.</p><p>Let’s review in detail some specific choices and which details and parameters we could pay attention to:</p><h3>A good font family</h3><p>In short, a <em>font family, </em>or <em>typeset </em>is a collection of fonts that share some geometric and stylistic attributes. <em>Helvetica</em> is a font family, whereas <em>Helvetica Back Condensed Oblique</em> would be a particular font within that family.</p><p>There are thousands of criteria that can be used to choose between the myriad of commercial and free available font families out there, but there are some that have a great impact on the legibility and clearness of your paragraphs:</p><ul><li><strong>Legible in a large size range</strong>. Don’t forget to test your font of choice in mobile devices, using the smaller size you are going to use. The text must be still completely legible.</li><li><strong>Distinguishable characters</strong>. What about “i” (the vowel), “l” (the consonant), and “1” (the number)? Do they look the same in your font? Then, maybe you must reconsider it, or you may sacrifice legibility in some words like “Illusion” or “Illustration”. In some cases like codes (“level l1”), it can be even worse.</li><li><strong>Available in all needed weights and variants</strong>. If you are going to use different weights (light, normal, bold, black…), ensure that are supported by your font, and although most browsers can convert any font to <em>italics</em> (faux italic), it will look much better if is supported by a specific font variant.</li><li><strong>Undisturbing, discrete and pleasant</strong>. Fancy fonts may look great on certain designs and placements, but paragraphs must use “boring” fonts that are comfortable to read.</li></ul><p>Of course, most of those requirements can be relaxed on titles and heading, but be careful with large bodies of text.</p><h3>Serif vs. Sans-Serif</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tW7HgRFwcf-vJr638Ijhzg.png" /><figcaption>Left: a Sans-Serif font (Open Sans). Right: a Serif font (Linux Libertine). Highlighted in red: the serifs</figcaption></figure><p>There is a traditional discussion on the legibility of the two great categories of font families: <a href="https://en.wikipedia.org/wiki/Serif">Serif</a> and <a href="https://en.wikipedia.org/wiki/Sans-serif">Sans-Serif</a>. Many designers dogmatically state that you must use serifs for printed media, and sans-serif for digital screens (that is, web and apps UIs)</p><p>Although it would have sense in the times of crappy CRT monitors that didn’t render properly the serifs (and even at that time, <a href="https://www.fonts.com/content/learning/fontology/level-1/type-anatomy/serif-vs-sans-for-text-in-print">that was relative</a>) the quality of current visualization hardware removes that criterium, as explains the guru of usability Jakob Nielsen. Actually, his UX research group made a study of the <a href="https://www.nngroup.com/articles/best-font-for-online-reading/">fastest to read fonts</a> (that is, more legible), and both families can be seen at the top.</p><p>So, don’t worry about serif and sans-serif: you will find excellent and very legible fonts for your website in both families.</p><h3>The perfect line length</h3><p>According to <a href="https://baymard.com/blog/line-length-readability">this study</a> by the <a href="https://baymard.com/">Maynard Institute</a>, the ideal number of characters in a line is between 50 and 75. There are objective reasons for those numbers:</p><ul><li>Lines with lots of characters make it harder for the user to focus on the text, and also may difficult positioning rightly to the next line.</li><li>Lines with few characters force the user to “jump” from one line to the other more times than he/she is used to doing, breaking the reading rhythm.</li></ul><p>In the case of mobile versions, probably it will be limited to the number of characters that fit the reduced width of the viewport.</p><h3>The perfect font size</h3><p>It’s not easy to set the right font size for an application. Many authors suggest using 16px but, of course, this may result in different optical sizes depending on the screen density and the device (in smartphones, <a href="https://juiceboxinteractive.com/blog/a-pixel-is-not-a-pixel-designing-for-a-new-generation-of-mobile-devices/">a pixel is not a pixel</a>), and, moreover, <strong>two fonts may have apparent different size for the same size value. </strong>Maybe that’s why accessibility and study groups like the <a href="https://www.w3.org/TR/WCAG21/">WCAG group</a> or <a href="https://www.ada.gov/">ADA</a> don’t explicitly ask for a particular font size value.</p><p>But always think that, in addition to visually impaired users (that may be more than what you think), sight gets worse with age, and <strong>seniors </strong>must be able to comfortably use your application.​​</p><p>My personal suggestion is that, in general, <strong>do not make them look smaller than the default font size of your target device.</strong>​ If you want to make it bigger than this, please do, but always follow the good old common sense.</p><h4>About CSS font size units</h4><p>There is an endless discussion between designers and developers about what unit to use when setting a font size in a CSS declaration.</p><p>Let’s review the most typical size units:</p><p><strong>pt </strong>is an absolute unit based on typographic points (72pt = 1 inch)</p><p><strong>px</strong> is an absolute unit based on screen pixels.</p><p><strong>em</strong> is a relative unit based on the font-size of the current element (i.e its div). 2em means <em>double </em>what the regular font size in this element would be.</p><p><strong>rem</strong> is a relative unit based on the font size of the root HTML element.</p><p>To guarantee a minimum level of accessibility, it is suggested to avoid absolute units as much as possible, to make it easy for users and devices to make fonts larger gracefully, for example, for visually impaired users.</p><p>Many front-end developers rely on the browser’s default font size and they just adjust this size between layout elements using <em>rem</em> units. This makes it very easy to create themes with different font sizes, and is considered a good accessibility practice.</p><p>You can read more about accessibility and font size units in <a href="https://css-tricks.com/accessible-font-sizing-explained/">this article</a>.</p><h3>Do we really need to justify it?</h3><p><em>Can you please justify it? It’s more elegant that way</em>. I heard that a lot of times from costumers applied to paragraphs of text.</p><p>Let’s remember what we are talking about:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rn6tvyE2d3hFFiV9jQ_-GA.png" /><figcaption>From left to right: Left-aligned text, justified text, and right-aligned text.</figcaption></figure><p>Putting personal preferences aside, there is a clear reason to choose left-aligned text (or <a href="https://en.wikipedia.org/wiki/Right-to-left_script">right-aligned</a> in the case of <a href="https://en.wikipedia.org/wiki/Right-to-left_script">RTL</a> languages): to justify a text, the text rendering engine (that part of the software that actually paints the characters on the screen) must add extra space between words. In some extreme cases, that space can make the text really weird:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*v9qeL9HjwBwe1aqQ_v6EfQ.png" /><figcaption>Wide blank spaces added to maintain justification. The effect is usually more prominent with short width columns.</figcaption></figure><p>Those artifacts can be minimized using hyphens (the dash with which we split words), but apart from the fact that some people are annoyed by it, it could be difficult for the rendering engine to properly split the words.</p><h3>A game of fonts</h3><p>We have reviewed several typographic criteria to choose a font and some of its attributes within a text body. But, what about <em>combining</em> fonts?</p><h4>Hierarchy</h4><p>The level of importance between the headings of the document must be reflected by the typography. First level headings font must be more prominent than second or third level headings. The obvious resource is the font size (highest font size for the first level headings), but be careful with other attributes of the fonts: if a second level heading is only slightly smaller, and its weight is way bigger, we could have a confusing hierarchy in which we are not sure about the levels of the headings.</p><h4>Contrast</h4><p>A nice way to imprint style and some eye-catching to our document or design piece is to assure that the different fonts have some degree of contrast. For example, we can use Serif fonts in first level headings or the document title, and sans-serif in second level or the subtitle. We can also combine different fonts of our font family, introducing variations in font weight or other parameters.</p><h4>Font count</h4><p>In general, unless we are doing some kind of complex piece of graphic design, it’s not a good idea to use more than 3 fonts in a document: two for the titles or headings, and the paragraphs font.</p><h3>Fonts and bytes: file formats and what to use</h3><p>There are three typical file formats in which font files are usually distributed:</p><ul><li>True Type (.ttf)</li><li>Open Type (.otf)</li><li>Postscript (.pfb, .pfm, .afm and others)</li></ul><p>Most fonts are distributed using TTF, OTF, or both. They are very similar and have better compatibility than Postscript. Open Type, however, has some additional advantages over True Type:</p><ul><li>Has better cross-platform and weird characters support, ​</li><li>Generally has less size​</li><li>Can be digitally signed​</li></ul><p>So go for this file format whenever possible.</p><h3>Putting all together</h3><p>As we have seen, typography is way more than <em>nice fonts</em>. It’s one of the pillars for successful user interaction with our product. Even when the specifications are provided by a designer, we are the ones that will transform their prototypes into a living product, and in this process, our knowledge about how a textual message is transmitted and perceived by the user will be crucial.</p><p>To summarize everything, let’s not forget that, as in all the decisions we make when designing and implementing our product, the<em> user, </em>its<em> intentions, </em>and<em> </em>his/her<em> satisfaction </em>when using it must be our priority. Every designer and front-end developer can have their own approach to this goal, but, as a suggestion, those are my guidelines to achieve a nice typographic design:</p><ul><li>Adjust sizes to make sure that all text is <em>legible</em> for all of our users.</li><li>Adjust spaces and alignments to make sure that all paragraphs are <em>pleasant</em> to read.</li><li>Choose font families to make sure that all glyphs are <em>beautiful</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=465696d285cb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edataconsulting/typography-tips-for-software-developers-465696d285cb">Typography tips for software developers</a> was originally published in <a href="https://medium.com/edataconsulting">edataconsulting</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with images to suit all]]></title>
            <link>https://medium.com/edataconsulting/working-with-images-to-suit-all-46468793cf02?source=rss----17e3ee3b4447---4</link>
            <guid isPermaLink="false">https://medium.com/p/46468793cf02</guid>
            <category><![CDATA[vector]]></category>
            <category><![CDATA[image]]></category>
            <category><![CDATA[web-design]]></category>
            <category><![CDATA[raster]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[Sara Gonzalez]]></dc:creator>
            <pubDate>Tue, 14 Jun 2022 09:19:27 GMT</pubDate>
            <atom:updated>2022-06-14T09:19:27.800Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jK6XYCKsrNktHxELm-ESMA.jpeg" /></figure><p>Hi, I’m Sara, Graphic and Web Designer at <a href="https://edataconsulting.com/">edataconsulting</a>!</p><p>During my career, there have been times when communication with clients or colleagues outside the profession has been hampered by a number of factors. Among those detected, those that have to do with the use of images and their technicalities.</p><p>Throughout this article, I’ll give you some design tips related to the use of images, how many different formats exist, which are the most common types, colour models… and a few more related topics.</p><p>All of them are some necessary technical concepts and tips to help you to be able to communicate your needs whenever you are working with images.</p><p>Let’s get started!</p><h4>Knowing image types</h4><p>While we are working on a project the first thing we need to identify is what kind of image type we are going to use: Raster images or Vector images. Most of you might be more familiar with the raster type, which is simply defined as the file composed of pixels. And on the other side we have the vector type, which is also commonly used but on the contrary, is not built by pixel but for the use of mathematical equations, lines, and curves with fixed points called ‘anchors’ on a grid to produce an image. I know I know, too technical but you’ll see in an image example.</p><p>These two image types are the most popular for visual content and the main differences between the two resides on the matter of resolution, the uses we give them, file sizes and compatibility.</p><p>To summarized and not to be too technical again, I just need to point out that while the raster type suffers from a loss of quality when the image is resized, this is not a problem for the vector type since we can resize and rescale infinite times without any loss. This provides a wide range of sizes, but when it comes to colours, there’s a huge difference between them. Vector types are displayed in solid ones while the huge amount of pixels gives the raster type the possibility of displaying a wider colour spectrum.</p><p><em>Here a visual approach on how a vector and a raster types looks like:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*McXhV0VuI7A-cATHtEH7uQ.jpeg" /><figcaption>Image credit: DINFOS Pavilion, Image source: pavilion.dinfos.edu</figcaption></figure><h4>Do you know which file format you should use?</h4><p>I’m sure you are already familiar with some file formats, but do you know in what context they should be used?</p><p>Both Raster and Vector types have a variety of file formats (jpg, png, gif, .bmp, .tiff: in the case of vectors: .svg, .ai, .eps…), but let’s concentrate on the three mostly used for website and printing purposes; those are the .jpg, .png and .svg file formats.</p><p>The first two formats correspond to a ‘Raster image type ’ and the last one to a ‘Vector image type’ and all of them are susceptible to be used in a website at the same time but not when it comes to printable uses, so we need to know when each of them are needed.</p><p>The Raster types we usually tent to use are the .jpg and the .png file formats, of course, with different colour modes for each purpose; but that’s a field in which we’ll be full submerge in a few lines, be patient.</p><p>The main difference between them is related to the compression of the file. While one of them -.jpg format- has a compression algorithm that affects the file size and sometimes can lead to a loss of quality, the other one -the png format- is not affected in that sense, since although it has a kind of compression algorithm type, this is based only in the perception of the images colour.</p><p><strong><em>So when do we need to use one or the other?</em></strong></p><p>Most of the time .png is needed when we require transparencies or images without backgrounds, which doesn’t support the .jpg file format. This last one, nevertheless, is more suitable in cases when we have a digital project with a considerable amount of images (i.e: software, website, apps…) and we need to speed up our page loading time.</p><p>And the last one but not less important, the .svg file format. On the contrary of .png and .jpg type, the .svg was designed purely to use on <strong>website</strong>. It is one of the lighter files and it never loses resolution, you can manipulate it dimensions without worrying for a lack of quality. So, this should be used on any graphic image susceptible of being resizable such as logotypes, iconography or illustrations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*lIe-N5FtL_hgnKTm_lBSOw.png" /></figure><h4>Colour Models. To suit all tastes they say, but not in this case.</h4><p>There are only two colour models for images: RGB and CMYK. They differentiated each other in how the colours are mixed and for that case, the uses we give them.</p><p>The RGB model is considered an additive mixing model in which each color -red, green and blue- all together in the same proportion (100%) creates a pure white and the absence of them creates black; but basically the entire colour spectrum are represented with the addition of every primary colour in this model. On the contrary, the CMYK or four-colour process is a subtractive model in which all the colours appear by deference of light on each tone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*lE2EsHbrZujbl7inkh7gdg.jpeg" /></figure><p>It is important to understand the difference in color models if you are going to work with or edit images for online or printed aims. But if you are not, don’t panic!</p><p>On this point you should only be concerned on using and being provided with RGB images from the clients or the external designers <strong>when it comes to online uses</strong>. In the case you need logos to be displayed on screen and the client doesn’t send you the vector format, just make sure they provide you with the RGB image, better if it is in the .png type.</p><p>And to finish to this block, the CMYK images are for <strong><em>printing purposes only</em></strong> so they should be only the priority for designers but if you are not lucky to have one to help you, just check that your document –business cards, posters, flyers, merchandise, etcetera- are exported with the CMYK colour model selected.</p><p><strong><em>How can we tell them apart at a glance?</em></strong></p><p>For non-designers or people not used to often manipulate images and without a tool that allows seeing the details of the image as photoshop or other free license program it could be difficult to detect of which type of image format we have in our possession. But there’s one simple trick that might help you:</p><p><strong>If you use the CMYK model for a digital image; the more colour you add to the picture, the darker the resulting mixture will be. But with the RGB model, is the opposite, the lighter the result will be. For that reason, images with a RGB color model are usually perceived in brighter colours while with CMYK model applied colours will appear duller.</strong></p><h4>Resolutions, Image Size &amp; File Size. The eternally misused terms.</h4><p>Probably, more than once, you have found yourself in a conversation with a designer asking for requirements, and been lost with all the technical terms we use coming out of our mouths. Let’s give you some explanations about them.</p><p>Sometimes we get confused between resolution and dimensions (image size) of an image. The resolution correspond to the number of pixels per inch in an image. So the more dots, the more quality we have.</p><p>The standard values are 72 dpi, 150 dpi and 300dpi. Each of them used for different purposes. On screens, the commonly used is the 72 dpi standard and for printed graphic material the optimal resolution is 300dpi.</p><p><em>But what happens if we want to reduce the resolution of an image? </em>Well, it will affect the quality in which the image is seen but not the file size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y5vXjOOo_nm4dX5oQ2uTKw.jpeg" /><figcaption>Image credit: Future</figcaption></figure><p>About the other two concepts… you will understand them very quickly. The <strong>image size</strong> is the dimensions and resolution of the image (pixels x pixels) all together and the <strong>File Size</strong> (measure in KB) correspond to the amount of space that the image takes up in your hard disk. Very simple, ha!</p><p>Therefore, knowing these concepts properly will help you not to be misunderstood during your conversation with designers.</p><h4>Follow these best practices</h4><p>In addition to all of the above considerations, whenever you are faced with a new project and need graphic material try to be sensitive to how you apply a brand, what image license you use and the quality of these, as well as the accessibility of your work to those who are visually impaired. Printed and digital resources should be available to all.</p><p>Here are some good practices that will make you a professional who is more aware of the appropriate use of images:</p><ul><li><strong>Follow the brand guidance</strong>. When working with brand images as we do, to apply them, we must first ask the client if they can provide us with a brand book, and therefore… follow the guidelines. If this brand book doesn’t exist, then apply the logotype without any transformation. Not changes of colours nor unproportionally rescale.</li><li><strong>Be aware of Right images. </strong>As you well know, there are different types of licenses available for image banks on the internet such as the creative common license. This type of license has also different rules, so when using a Creative Common Image we need to read the legal information just in case we must name the author; it is for non-commercial purposes or only to apply for personal uses.<br>We need to be careful to ensure that such images can be used in our projects and if that’s the case, be respectful with the work of others, i.e. mention the author.</li><li><strong>Accessibility</strong>. Apply each component available to images, such as aria-labels -in the case of websites-, so that they are well readable by screen readers.</li><li><strong>Hight-resolution images.</strong> When it is necessary to reduce the size of the image due to loading problems, make sure it has the least loss of display quality.</li><li><strong>Text readability.</strong> If we use text embedded in an image, we must ensure that it has enough contrast and a legible font.</li></ul><p>— — — — — — — — — —</p><p>I hope you’ll find this article interesting and that you’ve learned some new concepts. I am sure this will reduce your lack of knowledge and therefore your anxiety to express yourself in proper terms.</p><p>Just bear in mind this is just a new step towards being able to communicate your needs properly to clients, designers and colleagues at work. So, when you feel ready, go for it! Don’t hesitate to dive in with all your new vocabulary and implement good practice.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46468793cf02" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edataconsulting/working-with-images-to-suit-all-46468793cf02">Working with images to suit all</a> was originally published in <a href="https://medium.com/edataconsulting">edataconsulting</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Secure Your Web Application Part II: Securing Your Web Application With Spring Security]]></title>
            <link>https://medium.com/edataconsulting/how-to-secure-your-web-application-part-ii-securing-your-web-application-with-spring-security-5a876e2b5b76?source=rss----17e3ee3b4447---4</link>
            <guid isPermaLink="false">https://medium.com/p/5a876e2b5b76</guid>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-security]]></category>
            <dc:creator><![CDATA[Dustin Noah Young]]></dc:creator>
            <pubDate>Thu, 19 May 2022 14:12:53 GMT</pubDate>
            <atom:updated>2022-05-19T15:17:54.405Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gf7yj4NV7svIH3IpASd92A.jpeg" /></figure><p>Welcome to part 2 of this tutorial (if you haven’t yet, go check out <a href="https://medium.com/edataconsulting/how-to-secure-your-web-application-part-i-creating-a-web-app-with-spring-boot-and-angular-50d5e9e2fe96">part 1</a>). Before we move on, let’s have a look at what we’ve accomplished so far:</p><p>We have created a simple web application that functions as a fan page for a space-faring agency. The application consists of a back-end API that uses <a href="https://maven.apache.org/download.cgi"><strong>Maven</strong></a> and <a href="https://spring.io/projects/spring-boot"><strong>Spring Boot</strong></a><strong> </strong>for Java, and a front end that uses <a href="https://nodejs.org/en/"><strong>Node.js</strong></a> and <a href="https://angular.io/"><strong>Angular</strong></a>. Currently, a user can access three pages:</p><ul><li>Home — a page that displays announcements</li><li>Q&amp;A — a page that displays questions and answers</li><li>Users — a page that displays users</li></ul><p>When a user clicks on any of these pages, the front end will send a request to the respective endpoint in the back-end API in order to retrieve the data that should be displayed.</p><p>As of now, all three of these pages are unsecured, and in this article we are going to secure them using <a href="https://spring.io/projects/spring-security"><strong>Spring Security</strong></a>.</p><p>Our goal is to enforce the following rules to our pages:</p><ul><li>Home — shall remain accessible to anyone, with or without authentication</li><li>Q&amp;A — shall only be accessible to anyone who is authenticated</li><li>Users — shall only be accessible to anyone who is authenticated AND authorized to do so, meaning they need the right permissions for this</li></ul><p>You can find the code to this tutorial on <a href="https://github.com/DusDus3428/SpringSecurityExample/tree/app-secured"><strong>GitHub</strong></a> (git-checkout the branch ‘app-secured’). With that settled, let’s begin.</p><h3>Step 1: Adding A Database</h3><p>In order to properly demonstrate the authentication and authorization functionality of Spring Security, we are going to make some adjustments to the application. We are going to add a simple <a href="https://www.h2database.com/html/main.html"><strong>H2 database</strong></a> and populate it with some registered users. This will make our scenario a little more believable. Additionally, we will add <a href="https://hibernate.org/"><strong>Hibernate</strong></a> to manage the necessary queries to the database and adjust the code accordingly.</p><p>Let’s start by adding the H2 and Spring Boot Starter Data JPA (which includes Hibernate as the standard <a href="https://en.wikipedia.org/wiki/Jakarta_Persistence"><strong>JPA</strong></a> implementation) dependencies to the <em>pom.xml</em> file:</p><pre>...<br>&lt;dependencies&gt;<br>  ...<br>  &lt;dependency&gt;<br>    &lt;groupId&gt;com.h2database&lt;/groupId&gt;<br>    &lt;artifactId&gt;h2&lt;/artifactId<br>    &lt;scope&gt;runtime&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  ...<br>&lt;/dependencies&gt;<br>...</pre><p>H2 is an in-memory relational database written in Java. It’s perfect for testing and demonstration purposes, hence why we are using it here.</p><p>Since it’s designed as an in-memory database its nature is very volatile. When we start our application the database is created, and when we stop it the database is deleted. You can configure your H2 to store the data that you inserted or changed at runtime but we are not going to need that for this example. Nonetheless, we need to configure our app to use the database in the first place, and to do this we need to go to the <em>application.properties</em> file and add the following lines:</p><pre>spring.datasource.url=jdbc:h2:mem:spacedb // (1)<br>spring.datasource.driverClassName=org.h2.Driver // (2)<br>spring.datasource.username=sa // (3)<br>spring.datasource.password=sa // (3)<br>spring.jpa.database-platform=org.hibernate.dialect.H2Dialect // (4)<br>spring.jpa.hibernate.ddl-auto=none // (5)<br>spring.h2.console.enabled=true // (6)</pre><p>With these properties we are stating the following:</p><ol><li>The connection URL to the database.</li><li>The database driver that is needed for the connection.</li><li>User credentials to access the database. You can also leave the password empty if you want to.</li><li>The SQL dialect that Hibernate should use when communicating with the database.</li><li>Here we are stating that we do not want to use Hibernate for the <a href="https://en.wikipedia.org/wiki/Data_definition_language"><strong>DDL (Data Definition Language)</strong></a> generation process. That means that our table for registered users is not going to be generated using the entity definitions in our code. Instead, we are going to do that via an SQL file.</li><li>This simply lets us access the H2 console in a browser which is great for checking if our table has been created and populated with data. I will demonstrate this after we are done adding and configuring Spring Security.</li></ol><p>Next, let’s add the SQL files <em>schema.sql</em> and <em>data.sql</em> to our <em>src/main/resources</em> folder for the DDL and <a href="https://en.wikipedia.org/wiki/Data_manipulation_language"><strong>DML (Data Manipulation Language)</strong></a>, part. In our case, it’s enough to add a table for the registered users and to insert two users, one that is allowed to visit the Users page (an admin), and one that isn’t (a member).</p><p>Looking back at the first article, we hardcoded some user objects in the back end that are sent to the front end when the Users page is accessed. In order to avoid confusion, we shall call our database table <strong><em>t_registered_user</em></strong>. This way we can better differentiate between the objects of type <strong><em>User</em></strong><em> </em>(the data requested by the front end for display purposes) and the objects of type <strong><em>RegisteredUser </em></strong>(the actual user data with which the app can authenticate/authorize requests).</p><p>schema.sql</p><pre>DROP TABLE IF EXISTS t_registered_user;<br><br>CREATE TABLE t_registered_user (<br>    id INT AUTO_INCREMENT PRIMARY KEY,<br>    username VARCHAR(255) NOT NULL,<br>    password VARCHAR(255) NOT NULL,<br>    permission VARCHAR(255) NOT NULL<br>);</pre><p>data.sql</p><pre>INSERT INTO t_registered_user (username, password, permission) VALUES (&#39;Member&#39;, &#39;$2a$12$nz69C.Q21r95H3PB7YaLvOo/R6J8mHOSMEjTfR8JSXVR5FTGQrOPS&#39;, &#39;Member&#39;);<br><br>INSERT INTO t_registered_user (username, password, permission) VALUES (&#39;Admin&#39;, &#39;$2a$12$5YxjTJbYYjsOe6bDJ4CKg.rqoOrjbFemh5y.t6P/JzqI0tLGVnLLu&#39;, &#39;Admin&#39;);</pre><p>Notice that the passwords are encrypted here, as they should be. They are encrypted with the <a href="https://en.wikipedia.org/wiki/Bcrypt"><strong>BCrypt</strong></a><strong> </strong>algorithm which is the default for Spring Security. Just so we can test it later, here are the passwords:</p><pre>username: Member, password: member&lt;3</pre><pre>username: Admin, password: admin&lt;3</pre><p>After that, we need to create two new packages in our project: <strong><em>entity</em></strong> and <strong><em>repository</em></strong>. The project structure should now look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*L-PbUDiUkfebxNBvhbn4Dg.png" /></figure><p>In the <strong><em>entity</em></strong> package, we will add a class for our registered users.</p><p>RegisteredUser.java</p><pre>@Getter<br>@Setter<br>@Entity<br>@Table(name=&quot;t_registered_user&quot;)<br>public class RegisteredUser {<br>  @Id<br>  private long id;<br>  private String username;<br>  private String password;<br>  private String permission;<br><br>  protected RegisteredUser() {}<br>}</pre><p>Since we are using <a href="https://projectlombok.org/"><strong>Lombok</strong></a>, we can add the <strong><em>@Getter</em></strong> and <strong><em>@Setter</em></strong> annotations here so that we do not need to write the getter and setter methods ourselves.<br>The <strong><em>@Entity</em></strong> annotation is used to tell Hibernate that this is an entity class, meaning that this class represents a table in the database. We are also using the <strong><em>@Table</em> </strong>annotation to tell Hibernate what the table is called in the database. If we omit this, Hibernate will assume that there is a table called ‘RegisteredUser’. Since the names of the fields are equivalent to the column names of our table, we do not need to map them explicitly (although it could be done with the <strong><em>@Column</em></strong> annotation). The <strong><em>@Id</em></strong> annotation is an exception as it’s there to mark the field that holds a row’s unique identifier, and it’s required by JPA.</p><p>Now, we can add the repository which will be responsible for getting the registered users from the database to the <strong><em>repository</em></strong> package.</p><p>RegisteredUserRepository.java</p><pre>@Repository<br>public interface RegisteredUserRepository extends<br>  JpaRepository&lt;RegisteredUser, Long&gt; {<br>  <br>  RegisteredUser findByUsername(String username);<br>}</pre><p><strong><em>NOTE:</em></strong><em> The right thing to do would be to move all the data that the front end can request (announcements, posts for the Q&amp;A page, and users) to the database. After that, we would need to add the corresponding entities and repositories, and adjust the services accordingly. If you are not familiar with the JPA standard and/or ORMs like Hibernate, I can only encourage you to check them out.</em></p><h3>Step 2: Adding Spring Security to the Back End</h3><p>Now, the moment we have all been waiting for: let’s secure our app with Spring Security (if you want an introduction to Spring Security, go check out <a href="https://medium.com/edataconsulting/how-to-secure-your-web-application-part-i-creating-a-web-app-with-spring-boot-and-angular-50d5e9e2fe96">part 1</a>. I also have some links there for further reading).</p><p>To add Spring Security to your Maven app, go to the <em>pom.xml</em> file located in the root directory for the back end and add the following dependency:</p><pre>...<br>&lt;dependencies&gt;<br>  ...<br>  &lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId<br>  &lt;/dependency&gt;<br>  ...<br>&lt;/dependencies&gt;<br>...</pre><p>By doing this we have successfully added Spring Security to our app but we also want to configure it so that it behaves like we want it to. To do this, we must add another configuration file to our <em>config/</em> folder. This configuration file must fulfill the following points:</p><ul><li><strong>It needs to be annotated with the @EnableWebSecurity annotation</strong><br>This enables Spring Security’s web security support for our app</li><li><strong>It needs to extend the WebSecurityConfigurerAdapter class</strong><br>This provides the configuration class with methods that we can override in order to add our own configurations for Spring Security</li></ul><p>Now, by overriding the <strong><em>configure()</em></strong> method, we can configure Spring Security and tell it what endpoints to protect and which ones to leave alone.</p><p>WebSecurityConfiguration.java</p><pre>@Configuration<br>@EnableWebSecurity<br>public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {<br>  @Override<br>  protected void configure(HttpSecurity http) throws Exception {<br>    http<br>        .cors() // (1)<br>          .and()<br>        .httpBasic() // (2)<br>          .and()<br>        .authorizeRequests() // (3)<br>          .antMatchers(&quot;/user/&quot;).hasAuthority(&quot;Admin&quot;)<br>          .antMatchers(&quot;/&quot;, &quot;/announcement/&quot;, &quot;/login/&quot;, <br>            &quot;/h2-console/**&quot;).permitAll()<br>          .anyRequest().authenticated()<br>          .and()<br>        .headers().frameOptions().sameOrigin() // (4)<br>          .and()<br>        .csrf().disable(); // (5)<br>  }</pre><pre>  @Autowired<br>  @Qualifier(&quot;userDetailsService&quot;)<br>  UserDetailsService userDetailsService; <br><br>  @Autowired<br>  public void configureGlobal(AuthenticationManagerBuilder auth) <br>    throws Exception { <br>    <br>    auth.userDetailsService(userDetailsService)<br>      .passwordEncoder(new BCryptPasswordEncoder());<br>  }<br>}</pre><p>Let’s see what we did here:</p><ol><li>We’ve previously defined our <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS"><strong>CORS</strong></a> settings in <em>WebConfiguration.java</em>. To use those settings we need to register them with Spring Security (it will detect the settings automatically for us).</li><li>Here we enable <a href="https://en.wikipedia.org/wiki/Basic_access_authentication"><strong>Basic Auth</strong></a> (username + password combination).</li><li>If someone wants to access the <em>/user/ </em>endpoint they need to have the role ‘Admin’. <br>The endpoints <em>/</em>, <em>/announcement/</em>, <em>/login/</em>, and<br> <em>/h2-console/**</em> can be freely accessed by anyone, no authentication required.<br>Any other request requires the user to be authenticated.</li><li>By default the header for X-Frame-Options is set to ‘DENY’ by Spring Security. This disables rendering within an iframe which is done to prevent <a href="https://en.wikipedia.org/wiki/Clickjacking"><strong>Clickjacking</strong></a>. These attacks could allow an attacker to use CSS styling to make a user click on something that they were not intending. By setting this configuration we are only enabling it for requests within the same domain. This will allow us to use the H2 console in a browser.</li><li><a href="https://owasp.org/www-community/attacks/csrf"><strong>CSRF</strong></a> is an exploit in which an attacker sends a malicious request to a web application on behalf of an authenticated user unbeknownst to them. It’s a serious exploit that must be avoided at all costs. The impact such an attack can have on your application depends on the endpoints you have exposed and if they trigger a state change in your application (usually POST and PUT requests do this). <br>In our case, we just want to demonstrate the authentication and authorization processes, and the only POST request we have is the one for user authentication. To allow this POST request to come through, we will disable Spring Security’s CSRF protection for now (perhaps this can be covered by another article in the future).</li></ol><p>In the configuration class we can also see a <strong><em>UserDetailsService</em> bean</strong> and the <strong><em>configureGlobal()</em></strong> method. We’ll take a look at the former first.</p><p>We need to tell Spring Security how to authenticate users sending requests. In general, this part is highly dependent on how the application’s users are stored (e.g. directly in the application’s database, or in an external IdM — Identity Management — system). In our case, we store the users directly in the application’s database so we need to make sure that Spring Security is prepared for that.<br>To do that, we are going to create a service that implements the <strong><em>UserDetailService</em> interface</strong> provided by Spring Security. We will then override the <strong><em>loadUserByUsername()</em></strong> method and add the logic required to query the database for a registered user.</p><p>RegisteredUserService.java</p><pre>@Service(&quot;userDetailsService&quot;)<br>public class RegisteredUserService implements UserDetailsService {<br>    @Autowired<br>    private RegisteredUserRepository registeredUserRepository;<br><br>    @Override<br>    public UserDetails loadUserByUsername(String username) throws <br>      UsernameNotFoundException {<br>      RegisteredUser registeredUser = <br>        this.registeredUserRepository.findByUsername(username);<br><br>      if (registeredUser == null) {<br>        throw new UsernameNotFoundException(&quot;The user &quot; + username <br>          + &quot; is not a registered user.&quot;);<br>      }<br><br>      return registeredUser;<br>  }<br>}</pre><p>In the <strong><em>@Service</em></strong> annotation we define an internal name for the service. Spring will use that internal name to map this service directly to the <strong><em>UserDetailsService </em>bean</strong> that we annotated with the <strong><em>@Qualifier</em></strong> annotation in the configuration class.<br>As is evident in the implementation, the <strong><em>loadUserByUsername()</em></strong> method returns an object of type <strong><em>UserDetails</em></strong>. Since UserDetails is also an interface belonging to Spring Security, we are going to implement that too, but wait, we already have an entity for our registered users and it’s already mapped to the corresponding table in the database. Couldn’t we just use that?</p><p>Luckily, the answer is ‘yes’ (DRY FTW!).</p><p>RegisteredUser.java</p><pre>@Getter<br>@Setter<br>@Entity<br>@Table(name=&quot;t_registered_user&quot;)<br>public class RegisteredUser implements UserDetails {<br>  @Id<br>  private long id;<br>  private String username;<br>  private String password;<br>  private String permission;<br><br>  protected RegisteredUser() {}<br><br>  @Override<br>  public Collection&lt;? extends GrantedAuthority&gt; getAuthorities() {<br>    SimpleGrantedAuthority role = new <br>      SimpleGrantedAuthority(this.permission);<br>    return Collections.<em>singleton</em>(role);<br>  }<br>    <br>  //<br>  // The following methods will not be discussed in the article<br>  //<br><br>  @Override<br>  public boolean isAccountNonExpired() { return true; }<br><br>  @Override<br>  public boolean isAccountNonLocked() { return true; }<br><br>  @Override<br>  public boolean isCredentialsNonExpired() { return true; }<br><br>  @Override<br>  public boolean isEnabled() { return true; }<br>}</pre><p>When implementing the <strong><em>UserDetails</em> interface</strong>, you must also override some methods. As you can see, there is a method called <strong><em>getAuthorities()</em></strong> and it expects a collection of objects of type <strong><em>GrantedAuthority</em></strong> or subclasses of it. Registered users just have one role in our case, that role is named ‘permission’ and it’s a simple string object. So we can wrap permission in a <strong><em>SimpleGrantAuthority</em></strong> object, which implements the GrantedAuthority interface, and return it in the form of a collection.<br>We also need to override two more methods than are displayed in the code above: <strong><em>getUsername()</em></strong> and <strong><em>getPassword()</em></strong>. However, we are using Lombok’s <strong><em>@Getter</em></strong> annotation and it takes care of that for us.<br>The methods below the comment are not relevant for this article so just set their return values to ‘true’.</p><p>Now, to the <strong><em>configureGlobal()</em></strong> method in the configuration class:</p><pre>@Autowired<br>public void configureGlobal(AuthenticationManagerBuilder auth) <br>  throws Exception { <br>    <br>  auth.userDetailsService(userDetailsService)<br>    .passwordEncoder(new BCryptPasswordEncoder());<br>}</pre><p>Here we are basically telling Spring Security to use the <strong><em>UserDetailsService</em> bean</strong> we defined in the lines above and we are telling it to use the <strong><em>BCryptPasswordEncoder</em></strong> to encode the encrypted passwords we get from the database once a user tries to access a secured endpoint with an authentication header.</p><p>Now, just one more thing is missing for the back end. With Basic Auth, once a user logs in, they get a response back from the server that tells them if the authentication was successful or not. That is still missing on our side, so we will implement that in the form of a controller that leverages our previously defined service for registered users.<br>Upon successful authentication, we simply send back the user’s credentials, and if the authentication fails we send back a null value.</p><p>AuthenticationController.java</p><pre>@RestController<br>@RequestMapping(&quot;/login&quot;)<br>public class AuthenticationController {<br>  @Autowired<br>  RegisteredUserService registeredUserService;<br><br>  @PostMapping(&quot;/&quot;)<br>  public AuthenticationCredentials login(@RequestBody <br>    AuthenticationCredentials authenticationCredentials) {<br>    <br>    RegisteredUser registeredUser = (RegisteredUser)<br>      this.registeredUserService<br>      .loadUserByUsername(authenticationCredentials.getUsername());<br><br>    if (registeredUser == null) {<br>      authenticationCredentials = null;<br>    }<br><br>    return authenticationCredentials;<br>  }<br>}</pre><p>Let’s run our app with this command:</p><pre>mvn spring-boot:run</pre><p>In a browser, navigate to the URL <em>http://localhost:8080/rest/api/h2-console/</em>, we can login to the H2 console with the username and password we defined in the <em>application.properties</em> file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*jPFAZ_qDtDZf3Cw-uQVMzg.png" /></figure><p>Once we are logged in, we can see that the <strong><em>t_registered_user</em></strong><em> </em>table is present in the database. And by running a <strong>SELECT query</strong> we can retrieve the users we defined in the <em>data.sql</em> file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*c52XP3Nq311yIDKew3fw5w.png" /></figure><p>Now, let’s use <a href="https://www.postman.com/"><strong>Postman</strong></a> to test our secured back-end REST API. In the images below we can see that <em>http://localhost:8080/rest/api/announcement/</em> does not require any authentication headers to send the data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8U1laRcybXnyif27yAswcQ.png" /></figure><p>The same cannot be said about <em>http://localhost:8080/rest/api/questionAndAnswer/</em>. It requires valid credentials in the Basic Auth header:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ksW1w5RQmGpum8uqAU2I_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uCfPvlMDDOw7cLA7N9OgDQ.png" /></figure><p>While <em>http://localhost:8080/rest/api/user/</em> only works for users with the ‘Admin’ role:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*al3Qz3S-rcXnC6y-j5_c_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z9OlbVKC9__qj9cUuPY2ug.png" /></figure><p>And finally, we can see that you need valid credentials to perform a successful login (<em>http://localhost:8080/rest/api/login/</em>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bLOBlcFFyLAnzAJzBcvjnQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gL_pRJS7KhQezS6jmppHDQ.png" /></figure><h3>Step 4: Adding The Login And Logout Functionalities to The Front End</h3><p>Since we are now finished with securing our back end, all we have to do now is adjust the front end accordingly. For this, we need to add a login page and we also need to add some logic to send an authentication request and handle the response.</p><p>We can start with the Login page by adding a new component to our <em>component/</em> folder in the front end. For this, we can just execute the following command in a terminal:</p><pre>ng generate component login</pre><p>Now we just need to define the login form in the component’s HTML template and add a login button. Once the button is clicked a submit event is fired and the handler function <strong><em>login()</em></strong>, which is located in the component’s TypeScript file, will be executed.</p><p>login.component.html</p><pre>&lt;div&gt;<br>  &lt;h1 class=&quot;header&quot;&gt;Login&lt;/h1&gt;<br>  &lt;form [formGroup]=&quot;credentials&quot; class=&quot;contentList&quot;<br>    (submit)=&quot;login()&quot;&gt;<br>    <br>    &lt;div class=&quot;form-group row justify-content-center text-center&quot;&gt;<br>      &lt;label class=&quot;col-2&quot; for=&quot;username&quot;&gt;Username&lt;/label&gt;<br>      &lt;input class=&quot;col-3&quot; [formControlName]=&quot;&#39;username&#39;&quot; <br>        id=&quot;username&quot; type=&quot;text&quot;/&gt;<br>    &lt;/div&gt;<br>    &lt;br/&gt;<br>    &lt;div class=&quot;form-group row justify-content-center text-center&quot;&gt;<br>      &lt;label class=&quot;col-2&quot; for=&quot;password&quot;&gt;Password&lt;/label&gt;<br>      &lt;input class=&quot;col-3&quot; [formControlName]=&quot;&#39;password&#39;&quot; <br>        id=&quot;password&quot; type=&quot;password&quot;/&gt;<br>    &lt;/div&gt;<br>    &lt;br/&gt;<br>    &lt;div class=&quot;row justify-content-center text-center&quot;&gt;<br>      &lt;button class=&quot;col-2 button&quot; type=&quot;submit&quot;&gt;Login&lt;/button&gt;<br>    &lt;/div&gt;<br>  &lt;/form&gt;<br>  &lt;br/&gt;<br>  &lt;div <em>*ngIf</em>=&quot;showAuthenticationErrorMessage&quot;&gt;<br>    &lt;p class=&quot;warningMessage&quot;&gt;Warning: Authentication failed. Wrong <br>      username and/or password was used.&lt;/p&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p>login.component.ts</p><pre>@Component({<br>  selector: &#39;app-login&#39;,<br>  templateUrl: &#39;./login.component.html&#39;,<br>  styleUrls: [&#39;./login.component.scss&#39;]<br>})<br>export class LoginComponent implements OnInit {<br>  credentials: FormGroup;<br>  showAuthenticationErrorMessage: boolean = false;<br>  <br>  constructor(private authenticationService: AuthenticationService,<br>              private formBuilder: FormBuilder) { }<br><br>  ngOnInit(): void {<br>    this.credentials = this.formBuilder.group({<br>      username: &#39;&#39;,<br>      password: &#39;&#39;<br>    })<br>  }<br><br>  login() {<br>    this.authenticationService.login({<br>      username: this.credentials.get(&#39;username&#39;).value, <br>      password: this.credentials.get(&#39;password&#39;).value})<br>    .subscribe({<br>      error: error =&gt; {<br>        this.showAuthenticationErrorMessage = true;<br>      }<br>    })<br>  }<br>}</pre><p>It’s also important to note that we are using <a href="https://angular.io/guide/reactive-forms"><strong>reactive forms</strong></a> here. Since reactive forms define a model-driven approach we can define our form model as a form group comprised of two form controls: one for the username and one for the password. We do this using a <strong><em>FormBuilder</em></strong>, which allows us to use a simple syntax for the form definition. The <strong><em>[formGroup]</em></strong> and <strong><em>[formControl]</em></strong> directives in the HTML template allow us to bind our form to the model defined in the TypeScript file.<br>Once the user submits the form, the <strong><em>login()</em></strong> method is called. There the front-end service for authentication is used to send the username and password to the back end. If the authentication is not successful, an error message is displayed.</p><p>authentication.service.ts</p><pre>@Injectable()<br>export class AuthenticationService {<br>  private authenticatedUser:<br>    BehaviorSubject&lt;AuthenticationCredentials&gt;; // (1)<br>  public authenticatedUserAsObservable: <br>    Observable&lt;AuthenticationCredentials&gt;; // (1)<br><br>  constructor(private http: HttpClient,<br>              private router: Router) {<br>    this.authenticatedUser = <br>      new BehaviorSubject&lt;AuthenticationCredentials&gt;<br>      (<em>JSON</em>.parse(<em>localStorage</em>.getItem(&#39;user&#39;))); // (1)<br>    this.authenticatedUserAsObservable =<br>      this.authenticatedUser.asObservable(); // (1)<br>  }<br><br>  public login(credentials: AuthenticationCredentials) { // (2)<br>    return this.http.post&lt;AuthenticationCredentials&gt;<br>      (<em>environment</em>.backEndUrl<br>        .concat(RestEndpointConstants.<em>LOGIN_ENDPOINT</em>), <br>      {username: credentials.username, <br>      password: credentials.password})<br>    .pipe(map(response =&gt; {<br>      if (response.username) {<br>        <em>localStorage</em>.setItem(&#39;user&#39;, <em>JSON</em>.stringify(credentials));<br>        this.authenticatedUser.next(credentials);<br>        this.router.navigateByUrl(&#39;&#39;);      <br>      }<br>    }));<br>  }<br><br>  public logout() { // (3)<br>    <em>localStorage</em>.removeItem(&#39;user&#39;);<br>    this.authenticatedUser.next(null);<br>    this.router.navigateByUrl(&#39;/login&#39;)<br>  }</pre><pre>public getAuthenticatedUser() { // (4)<br>    return this.authenticatedUser.value;<br>  }<br>}</pre><ol><li>We have defined a <strong><em>BehaviorSubject</em></strong> called <strong><em>authenticatedUser</em></strong> that can emit a new object of type <strong><em>AuthenticationCredentials</em></strong>. In the constructor, we initialize it with an object called ‘user’ that is located in the local storage. This allows the service to keep track of an authenticated user in case of a browser refresh. If an item called ‘user’ does not exist, <strong><em>localstorage.getitem()</em></strong> returns a null value<strong> </strong>instead.<br>We have also defined an <strong><em>Observable</em> </strong>object<strong> </strong>called <strong><em>authenticatedUserAsObservable</em></strong>, and in the constructor, we initialize it as an observable of authenticatedUser. So every time authenticatedUser emits a new value, this observable will notify every component subscribed to it.</li><li>The <strong><em>login()</em></strong> method takes the user’s credentials as input and sends a POST request to the back end. If the response contains the username (authentication was successful), the user’s credentials are stored in the local storage, authenticatedUser emits them, and the user will be redirected to the Home page (the announcements page).<br><strong><em>NOTE:</em></strong><em> Basic Auth on its own is unsecure because the credentials are sent in an unencrypted fashion. We would have to use it in conjunction with </em><a href="https://en.wikipedia.org/wiki/HTTPS"><strong><em>HTTPS</em></strong></a><em> to make it more secure. This also applies to the request interceptor we are about to discuss. However, we will not implement this in this article.</em></li><li>The <strong><em>logout()</em></strong> method does not send anything to the back end, instead, it simply removes the user from the local storage, emits a null value to authenticatedUser, and redirects the user back to the login page.</li><li>We’ve also defined a getter for the value currently held by authenticatedUser — it will become relevant in the next paragraphs.</li></ol><p>This is all fine and good, but as soon as the user has logged in, how do we make sure to send the credentials to the back end every time we go to the Q&amp;A and Users pages? This is necessary so that Spring Security can determine whether the user is allowed to view that data or not. <br>We can ensure this by writing a request interceptor that implements Angular’s <strong><em>HttpInterceptor </em>interface</strong> and adding it to a new folder called <em>src/app/helpers/</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*PWmmY47NF30XDC_buLdbrA.png" /></figure><p>http-request-interceptor.ts</p><pre>@Injectable()<br>export class HttpRequestInterceptor implements HttpInterceptor {<br>  constructor(private authenticationService: AuthenticationService)<br>  {}<br><br>  intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler):<br>    Observable&lt;HttpEvent&lt;any&gt;&gt; {<br>    <br>    const user = this.authenticationService.getAuthenticatedUser();<br>    if (user) {<br>      request = request.clone({<br>        setHeaders: {<br>          Authorization: &#39;Basic &#39; + btoa(user.username + &#39;:&#39; <br>            + user.password)<br>        }<br>      })<br>    }<br>    return next.handle(request);<br>  }<br>}</pre><p>Every time the front end sends a request to the back end, it’s intercepted by this class and the <strong><em>intercept()</em></strong> method is executed. We use the getter method mentioned above to see if the user is already authenticated. If so, we add the credentials to the request’s <strong>authorization header</strong>.</p><p>Now, to finally bind everything together, there are still a few things we need to do.</p><p>First, we register <strong><em>AuthenticationService</em> </strong>and <strong><em>HttpRequestInterceptor</em> </strong>in the <strong><em>AppModule</em></strong>. Both are registered in the ‘providers’ section. Note that I have also added the <strong><em>ReactiveFormsModule</em> </strong>to the imports section. This is necessary since we are using reactive forms in our login component.</p><p>app.module.ts</p><pre>@NgModule({<br>  declarations: [<br>    AppComponent,<br>    UserComponent,<br>    QuestionAndAnswerComponent,<br>    AnnouncementComponent,<br>    LoginComponent<br>  ],<br>  imports: [<br>    BrowserModule,<br>    HttpClientModule,<br>    AppRoutingModule,<br>    ReactiveFormsModule<br>  ],<br>  providers: [<br>    AnnouncementService,<br>    QuestionAndAnswerService,<br>    UserService,<br>    AuthenticationService,<br>    DatePipe,<br>    { provide: <em>HTTP_INTERCEPTORS</em>, useClass: HttpRequestInterceptor, multi: true }<br>  ],<br>  bootstrap: [AppComponent]<br>})<br>export class AppModule { }</pre><p>Next, we add new buttons to the app component’s HTML template for the login and logout functionalities.</p><p>app.component.html</p><pre>&lt;nav class=&quot;navbar navbar-expand-md navbar-dark bg-dark&quot;&gt;<br>  &lt;div class=&quot;navigationBarTitle navbar-brand&quot;&gt;{{title}}&lt;/div&gt;<br>  &lt;a class=&quot;nav-tabs navigationBarLink&quot; routerLink=&quot;/&quot;&gt;Home&lt;/a&gt;<br>  &lt;a class=&quot;nav-tabs navigationBarLink&quot;<br>    routerLink=&quot;/questionsAndAnswers&quot;&gt;Q&amp;A&lt;/a&gt;<br>  &lt;a class=&quot;nav-tabs navigationBarLink&quot;<br>    routerLink=&quot;/users&quot;&gt;Users&lt;/a&gt;<br>  &lt;div class=&quot;authButtons&quot;&gt;<br>    &lt;a <em>*ngIf</em>=&quot;!authenticatedUser else <em>logoutButton</em>&quot; class=&quot;nav-tabs<br>      navigationBarLink&quot; routerLink=&quot;/login&quot;&gt;Login&lt;/a&gt;<br>    &lt;ng-template #<em>logoutButton</em>&gt;<br>      &lt;a class=&quot;nav-tabs navigationBarLink&quot; (click)=&quot;logout()&quot;&gt;<br>        Logout &lt;b&gt;{{authenticatedUser.username}}&lt;/b&gt;<br>      &lt;/a&gt;<br>    &lt;/ng-template&gt;<br>  &lt;/div&gt;<br>&lt;/nav&gt;<br>&lt;div class=&quot;componentContent&quot;&gt;<br>  &lt;router-outlet&gt;&lt;/router-outlet&gt;<br>&lt;/div&gt;</pre><p>And finally, we subscribe to the observable for the authenticated user in the authentication service and add the <strong><em>logout()</em></strong> method to <strong><em>AppComponent’s</em> </strong>TypeScript file.</p><p>app.component.ts</p><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.scss&#39;]<br>})<br>export class AppComponent {<br>  title: string = &#39;Space Travels Fan Page&#39;;<br>  authenticatedUser: AuthenticationCredentials;<br><br>  constructor(private authenticationService: AuthenticationService) <br>    {<br>    <br>    this.authenticationService.authenticatedUserAsObservable<br>      .subscribe(authenticatedUser =&gt; <br>        this.authenticatedUser = authenticatedUser<br>      );<br>    }<br><br>  logout() {<br>    this.authenticationService.logout();<br>  }<br>}</pre><p>With the back end still running, we can now run our front end and test if everything works as it should.</p><p>We can see that accessing Home does not require us to be logged in. However, when accessing Q&amp;A or Users we get a warning saying that the user must be logged in to view the page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*xLZy9aakOyd9WHrQ3iprqQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*BapWVTHv5MyPCUynIrffUQ.png" /></figure><p>The Login page also works as expected, and when logged in as the user ‘Member’ we can finally view the Q&amp;A page but not the Users page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*RJMcxhaUwUAIEp6PI6Y59w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*vSYtok1p00xKNUrWbQvmcg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*8vkqD5Vh2SvYfzIUwyZh-g.png" /></figure><p>However, if we are logged in as ‘Admin’, we can view the Users page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*i9OzYZmb8UUEQMdjws9E5A.png" /></figure><p>Logging in as an unknown user will result in a warning message appearing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*xg43RZKk-11QyxsD-ZBh2Q.png" /></figure><h3>Additional Adjustments</h3><p>To make the app a little nicer to look at and deal with I added and adjusted some styles and also added a component for the warning messages. Feel free to check the code for those changes if you are interested.</p><h3><strong>Conclusion</strong></h3><p>In this article, we managed to take our existing web application and secure the back-end REST API’s endpoints. We did this by adding an <strong>H2 database</strong> with some registered users, and by adding <strong>Spring Security</strong> to the back-end project and configuring it to behave as we want it to. We’ve also added a mechanism for the authentication process.<br>In the front end we added a <strong>login page</strong> and some <strong>logic to send authentication requests</strong> to the back end. We’ve also created an <strong>HTTP interceptor</strong> that adds an authenticated user’s credentials to the requests headers. <br>By running both projects and testing them together, we have proven that we now indeed have a secured web application.</p><p>And that about sums up our journey from creating an unsecured web application with <strong>Spring Boot</strong> and <strong>Angular</strong>, and securing it with Spring Security. I really hope these articles help and feel free to follow us on Medium in order to get notifications for more useful articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a876e2b5b76" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edataconsulting/how-to-secure-your-web-application-part-ii-securing-your-web-application-with-spring-security-5a876e2b5b76">How to Secure Your Web Application Part II: Securing Your Web Application With Spring Security</a> was originally published in <a href="https://medium.com/edataconsulting">edataconsulting</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Secure Your Web Application Part I: Creating a Web App With Spring Boot And Angular]]></title>
            <link>https://medium.com/edataconsulting/how-to-secure-your-web-application-part-i-creating-a-web-app-with-spring-boot-and-angular-50d5e9e2fe96?source=rss----17e3ee3b4447---4</link>
            <guid isPermaLink="false">https://medium.com/p/50d5e9e2fe96</guid>
            <category><![CDATA[tips]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Dustin Noah Young]]></dc:creator>
            <pubDate>Mon, 11 Apr 2022 08:37:08 GMT</pubDate>
            <atom:updated>2022-05-19T15:17:46.487Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TImzLU43fiL3lw51SK8zsw.jpeg" /></figure><p>Picture this scenario: a customer comes to us with an initial idea for a web application and gives us the freedom to make our own suggestions on how to build it (how cool is that?). We choose the technologies that best suit the needs of our customer and preferably ones in which our team is proficient (a dream come true). Then we start coming up with ideas on how to implement the different functionalities, which libraries to use, etc. when suddenly a thought arises: how are we going to secure this thing? (it was too good to be true)</p><p>As developers we love to write interesting algorithms to conquer complex problems and fulfill the customers’ needs. Ideally that is all we’d need to do but the truth is that securing web applications these days is a must and it’s becoming more and more relevant. Luckily, there are some great frameworks and libraries out there that can help us with these tasks. One such framework is called Spring Security and, as the name states, it is part of the vast Spring Framework.</p><h3>What is Spring Security?</h3><p>Here is a quick introduction to Spring Security taken from the <a href="https://spring.io/projects/spring-security"><strong>official documentation</strong></a>:</p><blockquote><em>‘Spring Security is a framework that focuses on providing both authentication and authorization to Java applications.</em>’</blockquote><p>In a nutshell, you can control who can access your application (authentication) and what parts of the application they can access or which actions they can perform (authorization). In fact, Spring Security offers much more than that, like protection against cross site request forgery (<a href="https://owasp.org/www-community/attacks/csrf"><strong>CSRF</strong></a>). Since exploring each feature of the framework would likely turn this tutorial into an eBook, we are just going to look at the authentication and authorization part.</p><h3>Prerequisites</h3><ul><li>Make sure you have OpenJDK 11 installed. I use <a href="https://docs.aws.amazon.com/corretto/latest/corretto-11-ug/what-is-corretto-11.html"><strong>Amazon Corretto</strong></a> for this tutorial but any other distribution should work as well</li><li>Make sure you have <a href="https://maven.apache.org/download.cgi"><strong>Maven 3.8.4 or higher</strong></a> installed</li><li>Make sure you have <a href="https://nodejs.org/en/"><strong>Node.js 16.14.0 or higher</strong></a> installed</li><li>Make sure you have <a href="https://angular.io/guide/setup-local"><strong>Angular 13</strong></a> installed</li><li>Make sure you have your favorite IDE installed. I’m using <a href="https://www.jetbrains.com/idea/"><strong>IntelliJ IDEA</strong></a></li><li>Create a root project folder with a fitting name. We will be using one project folder for both the back end and the front end</li></ul><h3>The Premise</h3><p>We are going to create an application that functions as a fan page for a space faring agency. The announcement page, or home page, will be accessible to anyone, the Q&amp;A page will be accessible to all authenticated users, and the user admin page will be accessible to authenticated users that are authorized to do so. We do not want unauthenticated and unauthorized users to see our Q&amp;A and user admin pages so we will use Spring Security to prevent that from happening.</p><p>Please note that this is just a very simple example for demonstration purposes only. You can find the code to this tutorial on <a href="https://github.com/DusDus3428/SpringSecurityExample/tree/app-unsecured"><strong>GitHub</strong></a> (git-checkout the branch ‘app-unsecured’). Now, without further ado, let’s begin.</p><h3>Step 1: Creating the Spring Boot Back End</h3><p>There are many ways to create a <a href="https://spring.io/projects/spring-boot"><strong>Spring Boot</strong></a> application and one of them is using the browser-based <a href="https://start.spring.io/"><strong>Spring Initializr tool</strong></a>. Click on the link and fill in the form as per the example depicted in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*Xg-cY5Gur8NVcejJleZg3g.png" /></figure><p>You may change the values for the fields <strong>Group</strong>, <strong>Artifact</strong>, <strong>Name</strong>, <strong>Description</strong>, and <strong>Package name </strong>to whatever you prefer.</p><p>Once you are done with that just click on <strong>‘Generate’</strong> and your new Spring Boot project will be downloaded to your computer as a ZIP file. Locate that file, extract its contents to your project folder, and open your root project folder in an IDE. Now we can create the Java packages we are going to need in the java folder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*yL5UhwuUQNfMOdecrHETNA.png" /></figure><p>You may choose the package structure that you prefer, however, please note that the packages <strong><em>config</em></strong>, <strong><em>controller</em></strong>, <strong><em>model</em></strong>, and <strong><em>service </em></strong>are often used in enterprise applications.</p><p>Next, we can go to the <em>pom.xml</em> file and add the <a href="https://projectlombok.org/"><strong>Lombok</strong></a> dependency. This will allow us to reduce some clutter in our model classes (we will get into that later):</p><pre>...<br>&lt;dependencies&gt;<br>  ...<br>  &lt;dependency&gt;<br>    &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>    &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>    &lt;version&gt;1.18.22&lt;/version&gt;<br>    &lt;scope&gt;provided&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>  ...<br>&lt;/dependencies&gt;<br>...</pre><p>In the <em>application.properties</em> file we can then add a single line to define our base API path:</p><pre>server.servlet.context-path=/rest/api</pre><p>With all that being done, we can go ahead and write the actual code for our API. Let’s start with the controller classes that will be located in our <strong><em>controller</em></strong><em> </em>package. Here we will leverage annotations provided by the Spring Framework to define our API endpoints.</p><p>AnnouncementController.java</p><pre>@RestController<br>@RequestMapping(&quot;/announcement&quot;)<br>  public class AnnouncementController {<br>    @Autowired<br>    private AnnouncementService announcementService;<br> <br>    @GetMapping(&quot;/&quot;)<br>    public List&lt;Announcement&gt; getAnnouncements() {<br>      return announcementService.getAnnouncements();<br>   }<br> }</pre><p>QuestionAndAnswerController.java</p><pre>@RestController<br>@RequestMapping(&quot;/questionAndAnswer&quot;)<br>public class QuestionAndAnswerController {<br>  @Autowired<br>  private QuestionAndAnswerService questionsAndAnswersService;<br> <br>  @GetMapping(&quot;/&quot;)<br>  public List&lt;QuestionAndAnswer&gt; getQuestionsAndAnswers() {<br>    return this.questionsAndAnswersService.getQuestionsAndAnswers();<br>  }<br>}</pre><p>UserController.java</p><pre>@RestController<br>@RequestMapping(&quot;/user&quot;)<br>public class UserController {<br>  @Autowired<br>  private UserService userService;<br> <br>  @GetMapping(&quot;/&quot;)<br>  public List&lt;User&gt; getUsers() {<br>    return this.userService.getUsers();<br>  }<br>}</pre><p>Let’s move on to the model classes that represent the data that will be retrieved from the back end and displayed in the front end. We will add a class for each information type — announcements, questions and answers, and users — to our <strong><em>model </em></strong>package. <br>Since questions and answers will share the same structure, we are only going to create one model class called <strong><em>Post</em></strong>, for both. Then we will create a <strong><em>QuestionAndAnswer </em></strong>class that contains a post for the question and one for the answer.</p><p>Announcement.java</p><pre>@Getter<br>public class Announcement {<br>  private String headline;<br>  private String text;<br>  private Date date;<br> <br>  public Announcement(String headline, String text, Date date){<br>    this.headline = headline;<br>    this.text = text;<br>    this.date = date;<br>  }<br>}</pre><p>Post.java</p><pre>@Getter<br>public class Post {<br>  private String text;<br>  private Date date;<br>  private String user;</pre><pre>  public Post(String text, Date date, String user){<br>    this.text = text;<br>    this.date = date;<br>    this.user = user;<br>  }  <br>}</pre><p>QuestionAndAnswer.java</p><pre>@Getter<br>public class QuestionAndAnswer {<br>  private Post question;<br>  private Post answer;<br>  <br>  public QuestionAndAnswer(Post question, Post answer){<br>    this.question = question;<br>    this.answer = answer;<br>  }<br>}</pre><p>User.java</p><pre>@Getter<br>public class User {<br>  private String username;<br>  private String email;<br>  private String role;<br> <br>  public User(String username, String email, String role) {<br>    this.username = username;<br>    this.email = email;<br>    this.role = role;<br>  }<br>}</pre><p>The <strong><em>@Getter</em></strong> annotation provided by the Lombok library automatically generates getters for the class members at compile time, so we don’t have to write them ourselves. The reason we need getters here is because we are using the Spring Framework for our REST API. Looking back at our controller classes, we can see that our endpoints return objects of the types we just defined. When sending a response, Spring will turn these objects into JSON objects as per our class definitions. Under the hood <a href="https://github.com/FasterXML/jackson"><strong>Jackson</strong></a> is used for the serialization and deserialization process and it requires the classes in question to provide getters for their members.</p><p>In our service package we will add services that will retrieve the information for us depending on which endpoint is called. Notice how we are skipping the repository and/or DAO layer for the sake of simplicity. Instead, our services will generate the objects we need.</p><p>AnnouncementService.java</p><pre>@Service<br>public class AnnouncementService {<br>  public List&lt;Announcement&gt; getAnnouncements() {<br>    Instant now = Instant.<em>now</em>();<br>    return new ArrayList&lt;&gt;() {{<br>      add(new Announcement(&quot;Important Announcement!&quot;, <br>          &quot;We are going to fly to Mars.&quot;, <br>          Date.<em>from</em>(now)));<br>      add(new Announcement(&quot;Important Announcement!&quot;, <br>          &quot;We are going to fly to the moon.&quot;, <br>          Date.<em>from</em>(now.minus(1, ChronoUnit.<em>DAYS</em>))));<br>      add(new Announcement(&quot;Important Announcement!&quot;, <br>          &quot;We are going to fly to space.&quot;, <br>          Date.<em>from</em>(now.minus(2, ChronoUnit.<em>DAYS</em>))));<br>    }};<br>  }<br>}</pre><p>QuestionAndAnswerService.java</p><pre>@Service<br>public class QuestionAndAnswerService {<br>  public List&lt;QuestionAndAnswer&gt; getQuestionsAndAnswers(){<br>    Instant now = Instant.<em>now</em>();<br><br>    QuestionAndAnswer questionAndAnswer1 = new QuestionAndAnswer(<br>      new Post(&quot;Why are you going to fly to space?&quot;,<br>        Date.<em>from</em>(now.minus(15, ChronoUnit.<em>DAYS</em>)),<br>        &quot;ilovespace78&quot;),<br>      new Post(&quot;Because we love weightlessness.&quot;,<br>        java.util.Date.<em>from</em>(now.minus(14, ChronoUnit.<em>DAYS</em>)),<br>        &quot;Bob&quot;));<br><br>    QuestionAndAnswer questionAndAnswer2 = new QuestionAndAnswer(<br>      new Post(&quot;Why are you going to fly to the moon?&quot;,<br>        Date.<em>from</em>(now.minus(5, ChronoUnit.<em>DAYS</em>)),<br>        &quot;ilovethemoon88&quot;),<br>      new Post(&quot;Because we love rocks.&quot;,<br>        java.util.Date.<em>from</em>(now.minus(4, ChronoUnit.<em>DAYS</em>)),<br>        &quot;Sheila&quot;));<br><br>    QuestionAndAnswer questionAndAnswer3 = new QuestionAndAnswer(<br>      new Post(&quot;Why are you going to fly to Mars?&quot;,<br>        Date.<em>from</em>(now.minus(1, ChronoUnit.<em>DAYS</em>)),<br>        &quot;ilovemars98&quot;),<br>      new Post(&quot;Because we can.&quot;,<br>        java.util.Date.<em>from</em>(now),<br>        &quot;Hope&quot;));<br><br>    return new ArrayList&lt;QuestionAndAnswer&gt;() {{<br>      add(questionAndAnswer1);<br>      add(questionAndAnswer2);<br>      add(questionAndAnswer3);<br>    }};<br>  }<br>}</pre><p>UserService.java</p><pre>@Service<br>public class UserService {<br>  public List&lt;User&gt; getUsers(){<br>    return new ArrayList&lt;&gt;() {{<br>      add(new User(&quot;ilovespace78&quot;, <br>        &quot;ilovespace78@spacespace.com&quot;, &quot;Member&quot;));<br>      add(new User(&quot;ilovethemoon88&quot;, <br>        &quot;ilovethemoon88@moonmoon.com&quot;, &quot;Member&quot;));<br>      add(new User(&quot;ilovemars98&quot;, <br>        &quot;ilovemars98@marsmars.com&quot;, &quot;Member&quot;));<br>      add(new User(&quot;Bob&quot;, <br>        &quot;bob@spacetravels.com&quot;, &quot;Admin&quot;));<br>      add(new User(&quot;Sheila&quot;, <br>        &quot;sheila@spacetravels.com&quot;, &quot;Admin&quot;));<br>      add(new User(&quot;Hope&quot;, <br>        &quot;hope@spacetravels.com&quot;, &quot;Admin&quot;));<br>    }};<br>  }<br>}</pre><p>Finally, to prevent <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS"><strong>CORS</strong></a> error messages from appearing when we call an API endpoint via our front end, we are going to add a web configuration class to our <strong><em>config </em></strong>package that will enable our front end (only our front end) to call any of our endpoints.</p><p>WebConfiguration.java</p><pre>@Configuration<br>@EnableWebMvc<br>public class WebConfiguration implements WebMvcConfigurer {<br>  @Override<br>  public void addCorsMappings(CorsRegistry registry) {<br>    registry.addMapping(&quot;/**&quot;)<br>      .allowedOrigins(&quot;http://localhost:4200&quot;);<br>  }<br>}</pre><p>To run the project, you just need to open a terminal in the back end’s project folder and type in the following command:</p><pre>$ mvn spring-boot:run</pre><p>After this, we can test the REST API with a tool like <a href="https://www.postman.com/"><strong>Postman</strong></a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*EiV0nWhZ60nvn5HE0w6Tgg.png" /></figure><h3>Step 2: Creating the Angular Front End</h3><p>To create the Angular front end, we can use the <a href="https://angular.io/cli"><strong>Angular CLI</strong></a>. Go into your root project folder, open a terminal, and write the following lines:</p><pre>$ ng new front-end-spring-security-example</pre><p>This will generate a new Angular project, and now we can simply add the folders we need:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*akgnChcdkZ4viSpv_FdKAw.png" /></figure><p>In the model package we should have the same data types we defined for the back end, just this time we need to think in TypeScript. We need to specify interfaces and not classes, since TypeScript interfaces are used for type-checking at compile time. To avoid redundancy, I will just show one of the interfaces here. Feel free to check out the <a href="https://github.com/DusDus3428/SpringSecurityExample/tree/app-unsecured"><strong>GitHub</strong></a> code or try converting the Java classes yourself:</p><pre>export interface Announcement {<br>  headline: string;<br>  text: string;<br>  date: Date;<br>}</pre><p>Next, we can create the services that send the GET requests to our back-end API. These will be in the <em>service/</em><strong> </strong>folder. Notice that we are using an object of the type <strong><em>HttpClient </em></strong>via dependency injection. This object allows us to easily build and send requests to REST APIs.</p><p>announcement.service.ts</p><pre>@Injectable()<br>export class AnnouncementService {<br>  constructor(private httpClient: HttpClient) {<br>  }<br>  <br>  public getAnnouncements(): Observable&lt;any&gt; {<br>    return this.httpClient.get(<strong><em>environment</em></strong>.backEndUrl<br>      .concat(RestEndpointConstants.<em>ANNOUNCEMENT_ENDPOINT</em>), <br>        {observe: &#39;body&#39;, responseType: &#39;json&#39;})<br>  }<br>}</pre><p>question-and-answer.service.ts</p><pre>@Injectable()<br>export class QuestionAndAnswerService {<br> <br>  constructor(private http: HttpClient) {<br>  }</pre><pre>  public getQuestionsAndAnswers(): Observable&lt;any&gt; {<br>    return this.http.get(<strong><em>environment</em></strong>.backEndUrl<br>      .concat(RestEndpointConstants.<em>QUESTION_AND_ANSWER_ENDPOINT</em>),    <br>        {observe: &#39;body&#39;, responseType: &#39;json&#39;})<br>  }<br>}</pre><p>user.service.ts</p><pre>@Injectable()<br>export class UserService {<br>  constructor(private http: HttpClient) {<br>  }<br>  <br>  public getUsers(): Observable&lt;any&gt; {<br>    return this.http.get(<strong><em>environment</em></strong>.backEndUrl<br>      .concat(RestEndpointConstants.<em>USER_ENDPOINT</em>), <br>        {observe: &#39;body&#39;, responseType: &#39;json&#39;});<br>  }<br>}</pre><p>The classes above use a constant called environment and an abstract class called <em>RestEndpointConstants,java</em>. As the name states, the latter is an abstract class that only contains the API endpoints in the form of constants. The corresponding file can be placed in the <em>config/ </em>folder:</p><pre>export abstract class RestEndpointConstants {<br> static readonly <em>ANNOUNCEMENT_ENDPOINT</em>: string = &quot;/announcement/&quot;;<br> static readonly <em>QUESTION_AND_ANSWER_ENDPOINT</em>: string =   <br>   &quot;/questionAndAnswer/&quot;;<br> static readonly <em>USER_ENDPOINT</em>: string = &quot;/user/&quot;;<br> }</pre><p>The environment constant is used to retrieve certain properties based on which environment is currently active (e.g., development, test, or production). In our case we are using the <em>environment.ts</em> file located in <em>environments/</em>, in which we can store the URL to our back-end API:</p><pre>export const <strong><em>environment </em></strong>= {<br>  production: false,<br>  backEndUrl: &#39;http://localhost:8080/rest/api&#39;<br>};</pre><p>For each page that we want to have we can now create the corresponding component in the <em>component</em><strong>/<em> </em></strong>folder. Each component is built in a similar fashion, so we will go into detail on one of them, the question-and-answer component. In our example only the <em>.component.ts</em> and <em>.component.html</em> files are important. In the TypeScript files we will use the services we defined earlier to get the desired information from our back end.</p><p>question-and-answer.component.ts</p><pre>@Component({<br>  selector: &#39;app-question-and-answer&#39;,<br>  templateUrl: &#39;./question-and-answer.component.html&#39;,<br>  styleUrls: [&#39;./question-and-answer.component.scss&#39;]<br>})<br>export class QuestionAndAnswerComponent implements OnInit {<br>  questionsAndAnswers: QuestionAndAnswer[] = [];<br> <br>  constructor(private questionAndAnswerService: <br>    QuestionAndAnswerService) { }</pre><pre>  ngOnInit(): void { <br>    this.questionAndAnswerService<br>      .getQuestionsAndAnswers()<br>      .subscribe(questionsAndAnswers =&gt; <br>        this.questionsAndAnswers = questionsAndAnswers)<br>  }<br>}</pre><p>Then in the template files we will use HTML and Angular’s <a href="https://angular.io/guide/interpolation"><strong>text interpolation</strong></a> to display the fetched information. Note that we are using the date pipe which is needed to transform the dates from timestamps to a human-readable format.</p><p>question-and-answer.component.html</p><pre>&lt;div <em>*ngIf</em>=&quot;(questionsAndAnswers &amp;&amp; questionsAndAnswers.length) else <strong><em>missingDataMessage&quot;</em></strong>&gt;<br>  &lt;h1 class=&quot;header&quot;&gt;Q&amp;A&lt;/h1&gt;<br>  &lt;ul class=&quot;contentList list-group list-group-flush&quot;&gt;<br>    &lt;li class=&quot;contentListItem list-group-item text-center&quot;<br>      <em>*ngFor</em>=&quot;let <strong><em>questionAndAnswer </em></strong>of questionsAndAnswers&quot;&gt;<br>      &lt;p class=&quot;postHeader&quot;&gt;Question from<br>        {{<strong><em>questionAndAnswer</em></strong>.question.user}} on<br>        {{<strong><em>questionAndAnswer</em></strong>.question.date | date:&#39;MM/dd/yyyy,<br>          \&#39;at\&#39; hh:mm:ss a&#39;}}&lt;/p&gt;<br>      &lt;p&gt;{{<strong><em>questionAndAnswer</em></strong>.question.text}}&lt;/p&gt;</pre><pre>      &lt;p class=&quot;postHeader&quot;&gt;Answer from<br>        {{<strong><em>questionAndAnswer</em></strong>.answer.user}} on<br>        {{<strong><em>questionAndAnswer</em></strong>.answer.date | date:&#39;MM/dd/yyyy,<br>          \&#39;at\&#39; hh:mm:ss a&#39;}}&lt;/p&gt;<br>      &lt;p&gt;{{<strong><em>questionAndAnswer</em></strong>.answer.text}}&lt;/p&gt;<br>    &lt;/li&gt;<br>  &lt;/ul&gt;<br>&lt;/div&gt;<br>&lt;ng-template #<strong><em>missingDataMessage</em></strong>&gt;<br>  &lt;p class=&quot;missingDataMessage&quot;&gt;Warning: Unable to fetch questions<br>    and answers.&lt;/p&gt;<br>&lt;/ng-template&gt;</pre><p>To tie everything together, we must use the app-routing module and the app module. In <em>app-routing.module.ts</em> we can define the routes to our three pages. Then in the <em>app.module.ts</em> file, we declare all the components we’ve defined, and all the providing services and the date pipe, and we also import the app-routing module.</p><p>app-routing.module.ts</p><pre>const routes: Routes = [<br>  { path: &#39;&#39;, component: AnnouncementComponent},<br>  { path: &#39;questionsAndAnswers&#39;, component:    <br>    QuestionAndAnswerComponent},<br>  { path: &#39;users&#39;, component: UserComponent}<br>];<br> <br>@NgModule({<br>  imports: [RouterModule.<em>forRoot</em>(routes)],<br>  exports: [RouterModule]<br>})<br>export class AppRoutingModule { }</pre><p>app.module.ts</p><pre>@NgModule({<br>  declarations: [<br>    AppComponent,<br>    UserComponent,<br>    QuestionAndAnswerComponent,<br>    AnnouncementComponent<br>  ],<br>  imports: [<br>    BrowserModule,<br>    HttpClientModule,<br>    AppRoutingModule<br>  ],<br>  providers: [<br>    AnnouncementService, <br>    QuestionAndAnswerService,<br>    UserService, <br>    DatePipe],<br>  bootstrap: [AppComponent]<br>})<br>export class AppModule { }</pre><p>And as a final touch we must add the navigational elements to our <em>app.component.html</em> file:</p><pre>&lt;nav class=&quot;navbar navbar-expand-md navbar-dark bg-dark&quot;&gt;<br>  &lt;div class=&quot;navigationBarTitle navbar-brand&quot;&gt;{{title}}&lt;/div&gt;<br>    &lt;a class=&quot;nav-tabs navigationBarLink&quot; routerLink=&quot;/&quot;&gt;Home&lt;/a&gt;<br>    &lt;a class=&quot;nav-tabs navigationBarLink&quot;<br>      routerLink=&quot;/questionsAndAnswers&quot;&gt;Q&amp;A&lt;/a&gt;<br>    &lt;a class=&quot;nav-tabs navigationBarLink&quot; <br>      routerLink=&quot;/users&quot;&gt;Users&lt;/a&gt;<br>&lt;/nav&gt;<br>&lt;div class=&quot;componentContent&quot;&gt;<br>  &lt;router-outlet&gt;&lt;/router-outlet&gt;<br>&lt;/div&gt;</pre><p>At this point I would like to point out that we have not gone into the styling process for our front end since it is not the subject of this article. However, I would like to help you get started if you are interested in the app’s UI design. I’ve styled the app you can find on <a href="https://github.com/DusDus3428/SpringSecurityExample/tree/app-unsecured"><strong>GitHub</strong></a>, so if you like you can just apply the ones I added there.<br>In order to quickly apply some styling you just need to open a terminal in your front-end folder and install the <a href="https://www.npmjs.com/package/bootstrap"><strong>bootstrap</strong></a> and <a href="https://www.npmjs.com/package/jquery"><strong>jquery</strong></a> packages:</p><pre>$ npm install bootstrap jquery --save</pre><p>Next, you need to open the <em>angular.json</em> file to add some styles and some scripts:</p><pre>&quot;styles&quot;: [<br>  &quot;src/styles.scss&quot;,<br>  &quot;node_modules/bootstrap/dist/css/bootstrap.min.css&quot;<br>],<br>&quot;scripts&quot;: [<br>  &quot;node_modules/jquery/dist/jquery.min.js&quot;,<br>  &quot;node_modules/bootstrap/dist/js/bootstrap.min.js&quot;<br>]</pre><p>And after that you are all set to add your own styles to the different SCSS files that you will find for each component.</p><p>At last, the moment of truth: running both applications and testing the endpoints. With the back end still running, open a command line or terminal in the front-end app and type in this command:</p><pre>$ npm run start</pre><p>Open a browser and type in the URL <em>http://localhost:4200</em>, and voila! We now have a web app that is totally unsecured.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*PBvSO-PpCHp0TfypTGlHQQ.png" /></figure><h3>Conclusion</h3><p>In this article we discussed how to build an unsecured web application with a REST API back end based on Spring Boot and Java, and a front end based on Node.js and Angular.</p><p>In part 2 of this series, we are going to go into detail on how to secure the web app. You can check it out <a href="https://medium.com/edataconsulting/how-to-secure-your-web-application-part-ii-securing-your-web-application-with-spring-security-5a876e2b5b76"><strong>here</strong></a>. <br>Also, don’t forget to follow us on Medium to receive notifications about other articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50d5e9e2fe96" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edataconsulting/how-to-secure-your-web-application-part-i-creating-a-web-app-with-spring-boot-and-angular-50d5e9e2fe96">How to Secure Your Web Application Part I: Creating a Web App With Spring Boot And Angular</a> was originally published in <a href="https://medium.com/edataconsulting">edataconsulting</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>