<?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[Stories by Philip Lysenko on Medium]]></title>
        <description><![CDATA[Stories by Philip Lysenko on Medium]]></description>
        <link>https://medium.com/@philip_lysenko?source=rss-4501ab28e9c0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GStJJkUefF_-YKfcfVPmkQ.jpeg</url>
            <title>Stories by Philip Lysenko on Medium</title>
            <link>https://medium.com/@philip_lysenko?source=rss-4501ab28e9c0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 04:59:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@philip_lysenko/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Angular Universal with Nrwl Nx]]></title>
            <link>https://medium.com/@philip_lysenko/angular-universal-with-nrwl-nx-ca2996a7da2?source=rss-4501ab28e9c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca2996a7da2</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nrwl]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Philip Lysenko]]></dc:creator>
            <pubDate>Sat, 15 Jun 2019 10:28:19 GMT</pubDate>
            <atom:updated>2019-06-15T10:28:19.961Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W93virD7syBFz-n_GIz8Xg.png" /></figure><h4>Bootstrapping a Nrwl Nx Workspace with Angular-Universal</h4><p><a href="https://angular.io/guide/universal">Angular Universal </a>is a project for Angular allowing Server-Side-Rendering, allowing faster loading times and better SEO.<br><a href="https://nx.dev/">Nx</a> is a project by Nrwl, a company of former Google engineers, trying to share some of Google’s best practices with us plebs. The biggest advantage of Nx is its <a href="https://nx.dev/fundamentals/develop-like-google">tooling and bootstrapping</a> support for mono-repos. A mono-repo is simply a way of managing multiple applications with shared libraries in a single workspace.<br>However, bootstrapping an Angular app with Nx schemas does not work so well with Angular Universal yet. This tutorial will help with that ❤️.</p><h4>1. Generate the app</h4><p>Starting from scratch, let us download the Angular-CLI and NX globally:</p><pre>npm install -g @angular/cli<br>npm install -g @nrwl/schematics</pre><p>Now let us generate a new workspace called “workspace” and a new app called “blog”:</p><pre>create-nx-workspace blog<br>Prompt CSS =&gt; Choose SCSS<br>Prompt npm-scope =&gt; type “workspace” for aliases like “@workspace”<br>Prompt framework =&gt; Choose “none” for now<br>cd workspace<br>ng g app blog<br>Prompt framework =&gt; choose Angular<br>Prompt directory =&gt; press enter (default)<br>Prompts unit-tester =&gt; choose Jest (❤️)<br>e2e-tester =&gt; choose Cypress (❤️❤️)<br>tags =&gt; write “app, blog-app” (or whatever you want)</pre><p>Now you should have a workspace with a structure like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*mCQsdeuJ-qmgas1_uTGRJg.png" /></figure><p>Let us utilise native Angular-CLI schematics to try and bootstrap Angular Universal into the project:</p><pre>ng add <a href="http://twitter.com/nguniversal/express-engine">@nguniversal/express-engine</a> --clientProject blog</pre><p>The schematics will generate all the files that we need, but some of them will be placed in the wrong place (for a mono-repo) and they will not be linked correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*py0zf5uMcYpjLIkJAI_lBg.png" /><figcaption>server.ts and webpack.server.config.js were generated in the root directory of the workspace. We want to put them in apps/blog instead. Also note the new commands in package.json.</figcaption></figure><h4>2. Bootstrap everything</h4><p>Our goals for the rest of the tutorial will be to</p><ol><li>To put server.ts and webpack.server.config.js in apps/blog</li><li>To make Angular generate the server- and browser-output in dist/apps/blog/server/ and dist/apps/blog/browser/, respectively</li></ol><p>But let’s start step-by-step. If we try to execute the newly generated <a href="https://angular.io/guide/universal#universal-in-action">package.json-commands</a></p><pre>npm run build:ssr &amp;&amp; npm run serve:ssr</pre><p>… we will get the error that the file (for production file-replacement ) at path /workspace/src/environments/environment.prod.ts was not found. In angular.json change the server-fileReplacements to have the apps/blog-prefix:</p><pre>&quot;server&quot;: {<br>  ...<br>  &quot;configurations&quot;: {<br>    &quot;production&quot;: {<br>      &quot;fileReplacements&quot;: [<br>        {<br>          &quot;replace&quot;: &quot;apps/blog/src/environments/environment.ts&quot;,<br>          &quot;with&quot;: &quot;apps/blog/src/environments/environment.prod.ts&quot;<br>        }<br>      ]<br>    }<br>  }<br>}</pre><p>If you execute the commands now, you might get some confusing Cypress-related errors. But don’t worry, once we fix our project structure, they will go away.</p><p>So let’s move server.ts and webpack.server.config.js into apps/blog. server.ts will produce some typescript-compilation errors (“require”, “path” etc cannot be found) because tsconfig.app.json contains the line:</p><pre>&quot;types&quot;: []</pre><p>…overriding “node”-types from the root-level tsconfig.json; delete this line ☠️</p><p>The other files generated for Angular Universal inside apps/blog are ok as they are and we don’t have to touch them for the rest of the tutorial.</p><p>Now let’s adjust two paths in server.ts according to our desired dist-folder structure:</p><pre>const DIST_FOLDER = join(process.cwd(), &#39;dist&#39;, &#39;apps&#39;, &#39;blog&#39;, &#39;browser&#39;);<br><br>const {AppServerModuleNgFactory, LAZY_MODULE_MAP} = require(&#39;../../dist/apps/blog/server/main&#39;);</pre><p>And in webpack.server.config.js link to the moved server.ts file and also adjust the output directory:</p><pre>server: &#39;./apps/blog/server.ts&#39;</pre><pre>output: {<br>    path: path.join(__dirname, &#39;../../dist/apps/blog/server&#39;),<br>    filename: &#39;[name].js&#39;<br>  },</pre><p>Now inside package.json, link the compile:server-command to the moved webpack.server.config.js and link the serve:ssr-command to the new output directory:</p><pre>&quot;compile:server&quot;: &quot;webpack --config apps/blog/webpack.server.config.js --progress --colors&quot;,</pre><pre>&quot;serve:ssr&quot;: &quot;node dist/apps/blog/server/server&quot;,</pre><p>Now that we expect our output to be in dist/apps/blog, let us instrument Angular to actually put it there. In angular.json change the paths for the browser and the server output:</p><pre>&quot;architect&quot;: {<br>  &quot;build&quot;: {<br>    &quot;builder&quot;: &quot;<a href="http://twitter.com/angular">@angular</a>-devkit/build-angular:browser&quot;,<br>    &quot;options&quot;: {<br>      &quot;outputPath&quot;: &quot;dist/apps/blog/browser&quot;,</pre><pre>&quot;server&quot;: {<br>  &quot;builder&quot;: &quot;<a href="http://twitter.com/angular">@angular</a>-devkit/build-angular:server&quot;,<br>  &quot;options&quot;: {<br>    &quot;outputPath&quot;: &quot;dist/apps/blog/server&quot;,</pre><p>While you are in angular.json, you might as well add the following to server.configurations:</p><pre>&quot;sourceMap&quot;: false,<br>&quot;optimization&quot;: true</pre><p>This will remove the source maps and optimize/minify the server-output. Otherwise at the end you will get a source map like this for your main.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*XKvUGLJQzUYzvTDMiqW9Iw.png" /></figure><h4>3. Profit!</h4><p>You can verify that you did everything correctly by running this command again:</p><pre>npm run build:ssr &amp;&amp; npm run serve:ssr</pre><p>On <a href="http://localhost:4000/">http://localhost:4000</a> you should now be able to see the server-side app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N8HliUzePwA9Xhm1ExixyA.png" /></figure><p>You can tell it is prerendered because the &lt;body&gt;-tag contains more than just an empty root-tag, but actual HTML-tags like &lt;div&gt;, &lt;h1&gt; etc inside of it. You can also serve the browser-side app as usual to see the difference.</p><h4>4. Summary</h4><p>You can find the code from this tutorial here:</p><p><a href="https://github.com/philly-vanilly/nrwl-nx-angular-universal-starter">philly-vanilly/nrwl-nx-angular-universal-starter</a></p><p>If you found this tutorial useful, please 👏 one or few times! Also big thanks to Stefan Karlsson for the help on Stackoverflow!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca2996a7da2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Initial Auth with Angular & OAuth2]]></title>
            <link>https://medium.com/@philip_lysenko/initial-auth-with-angular-oauth2-a8740efe9264?source=rss-4501ab28e9c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8740efe9264</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Philip Lysenko]]></dc:creator>
            <pubDate>Sun, 12 May 2019 17:51:13 GMT</pubDate>
            <atom:updated>2019-05-30T08:41:34.328Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5KhxBO5C7Xebbmafarn0JQ.jpeg" /><figcaption><strong>Only bikers can get in?</strong> (Photo by <a href="https://unsplash.com/photos/oqqEC31VT7I?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Alex Iby</a> on <a href="https://unsplash.com/search/photos/club?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a>)</figcaption></figure><h3>Logged-In-Only Access with Angular-OAuth2-OIDC</h3><p>You can find many tutorials online about integrating OAuth2 / OIDC in your Angular app. Most of them tell you how to configure a lib like <a href="https://github.com/manfredsteyer/angular-oauth2-oidc">angular-oauth2-oidc</a> or <a href="https://github.com/auth0/auth0.js">auth0.js</a> inside an authorisation service, which redirects to the login-page upon the click of a “Login”-button. But what if you don’t want to display your app page for logged-out users at all? Every time the user visits your site, he is supposed to be greeted by the authorisation-server (e.g. the “login-page”) directly. This is a very common pattern when you develop some sort of a user-terminal application.</p><p>To see what I mean, check out the deployed final result of this tutorial:<br><a href="https://philly-vanilly.github.io/init-auth">https://philly-vanilly.github.io/init-auth</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*-oZrtI6SnrUKmt2LaLEVtQ.png" /><figcaption>First the login-page, then the main page</figcaption></figure><blockquote>Note: OIDC and OAuth2 are basically the same protocol, with the exception that with OIDC you also receive an id token containing user-information. I will refer to both protocols simply as OAuth2.</blockquote><p>A naive integration approach would be to simply call your authorisation service inside the constructor of the app.component. But this way the user has to download the whole app.module with all its dependencies before the actual redirect.<br>Ideally, you would just load the authorisation code before app initialisation and make it either redirect to the login-page or (in case that the call is a redirect back from the login-page) to setup the auth-data provided inside the access token.</p><p>Now you could accomplish this “initial auth” in two ways:</p><ul><li>Angular way: implementing APP_INITIALIZER and utilising lazy loading</li><li>VanillaJS way: validate the token inside index.html with a &lt;script&gt; tag</li></ul><p>The VanillaJS approach can potentially make the initial load smaller, as Angular’s BrowserModule, RouterModule and HttpClientModule do not have to be loaded. However, those modules are only few hundred kb in size anyway and can be cached in the browser. Also, trying it out for angular-oauth2-oidc I realized the lib requires at least NgZone and HttpClient from Angular, so the size savings would probably be not as big as expected. More importantly, the vanilla approach requires bundling the auth lib from NPM yourself without the help of Angular CLI, making the app less maintainable. Writing your own token verification code (e.g. not using a lib) is also discouraged as this would be another case of reinventing the wheel.</p><p>So we will stick with the Angular approach. It does have one bigger downside though which is that you have to add an additional route fragment for the lazy loading. So you need to adjust all your routes accordingly; in a bigger app this might take time, but at least it is straightforward.</p><h3>1. Make your main app.module lazily loaded</h3><p>First thing you need to do is to introduce a new initial component that contains only a &lt;router-outlet&gt; …</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b162fb3a73805ae94c0a6d12ea084246/href">https://medium.com/media/b162fb3a73805ae94c0a6d12ea084246/href</a></iframe><p>… and a respective url-path-fragment for the lazily loaded module:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d040c6abf3e6ad7740eb045075329d9/href">https://medium.com/media/7d040c6abf3e6ad7740eb045075329d9/href</a></iframe><p>LazyModule in this example will be your old AppModule and the new AppModule will contain only this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/600178661d27be12616afa44f51032a4/href">https://medium.com/media/600178661d27be12616afa44f51032a4/href</a></iframe><h3>2. Implement APP_INITIALIZER</h3><p>Now let’s take a look at the AuthModule imported by AppModule:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfa83269ed32f4393c1e38406fec68fa/href">https://medium.com/media/bfa83269ed32f4393c1e38406fec68fa/href</a></iframe><p>Here we provide an arrow function which implements APP_INITILIZER. This function gets executed by Angular on startup before any component is loaded. It always has to be provided inside the initial app.module. This is why we try to make app.module as tiny as possible; for example note how our AppComponent consists only of a router-outlet. In a real app the UI-modules and other heavy stuff would be placed in LazyModule.</p><blockquote>Note: if you are not familiar with APP_INITILIZER, it allows you to run functions upon a module’s initialisation. You might be familiar with implementing a static forRoot (in an eager module) or forChild (in a lazy module) function like <a href="https://medium.com/@chrishouse/when-to-use-angulars-forroot-method-400094a0ebb7">here</a>. But these functions are only meant to return a ModuleWithProvider object from them in order to setup the module based on parameters. Any code that can’t be processed at compilation-time will throw an error in production when using AOT-compilation. To execute runtime code implement APP_INITILIZER instead.</blockquote><p>Now let’s take a look at the implementation of the AuthService:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e8273370de84132ec03fc9beb4af650/href">https://medium.com/media/1e8273370de84132ec03fc9beb4af650/href</a></iframe><blockquote>Note: In this case we are utilising the angular-oauth2-oidc lib, which works well with Auth-Servers like Keycloak or Identity-Server 4. For Auth0 or some other auth/id-provider you might consider using a different lib.</blockquote><p>Upon an initial call of the app, we initialise the OAuth2 Implicit Flow (recommended for Single Page Applications like Angular), which means that we will be redirected to the external login page and be redirected back on successful login with all the data provided directly on the redirect (server-side rendered apps, e.g. PHP e.t.c. would make one more additional call). We prevent further loading of the app with a reject-callback.</p><p>After the redirect back to the app from the login-page, our auth-lib will recognise our logged-in status and this time call a success-callback, which will initialise the rest of the app. You might also want to decode the initial and refresh tokens here (every time there is an update-event), so when other parts of the app (e.g. guards) want to check the necessary permissions from the access-token or some components to display user-data from the id-token, they don’t have to decode them again.</p><p>You should also remove the redirect-hash (#state=xxxx) from the URL before the success-callback. Otherwise, if you are using the <a href="https://medium.com/lacolaco-blog/introduce-router-scroller-in-angular-v6-1-ef34278461e9">hash-fragment-scrolling</a>, Angular router will throw an error on app-initialisation, freezing the app. The angular-oauth2-oidc lib removes the hash with a flag in the config; with other libs, you might need to do it manually by using Injector to get the router (see the commented out part of code).</p><h3>That’s it!</h3><p>Here is the full code of this deployed (see link at the top) prototype with additional comments and example-guards:</p><p><a href="https://github.com/philly-vanilly/init-auth">philly-vanilly/init-auth</a></p><p>If you found the tutorial helpful, please 👏 one or more times ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8740efe9264" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical Introduction to Web-Security with Angular and Nginx (Part 2)]]></title>
            <link>https://medium.com/@philip_lysenko/practical-introduction-to-web-security-with-angular-and-nginx-part-2-460c67527dac?source=rss-4501ab28e9c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/460c67527dac</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[web-hosting]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[nginx]]></category>
            <dc:creator><![CDATA[Philip Lysenko]]></dc:creator>
            <pubDate>Sat, 11 Aug 2018 20:25:48 GMT</pubDate>
            <atom:updated>2018-11-21T08:06:38.036Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ghD739LQ1ZyS3IIIVAhoyg.jpeg" /></figure><p>In the previous part we configured a basic Angular and Nginx setup in a Docker container, including configuration for HTTPS. In this part we want to learn about Man-In-The-Middle-Attacks which HTTPS protects us against and strengthen our HTTPS configuration.</p><h4>Revision</h4><p>You can find the result code at the point where we left off here: <a href="https://github.com/philly-vanilly/angular-nginx/tree/fbf04e9acdc60da57d4d24d9b748bea091a123e7">https://github.com/philly-vanilly/angular-nginx/tree/fbf04e9acdc60da57d4d24d9b748bea091a123e7</a></p><p>If something doesn’t work for you, please check out the last part again:</p><p><a href="https://medium.com/@philip_lysenko/basic-web-security-with-angular-and-nginx-535fa5a2a866">Practical Introduction to Web-Security with Angular and Nginx (Part 1)</a></p><p>At least you should remember these terminal commands from it:</p><pre>docker build -t angular-nginx . &amp;&amp; docker run -p 80:80 -p 443:443 -it angular-nginx<br>httpobs-local-scan --http-port 80 --no-verify localhost</pre><h4>HSTS</h4><p>In the previous part we have forced all requests to be redirected to a second server that only serves over HTTPS (e.g. with TLS encryption enabled). So are we safe from the man in the middle now? Not quite yet. One scenario to be aware of is that a user calls the non-encrypted-version of your site and an attacker (like an evil-minded WiFi host) intervenes before your own server can redirect him to HTTPS safe-space. This actually happens a lot, since most Internet users just input a domain-name in the address-bar, which then could be resolved to a non-TLS endpoint, unless the user has browser-plugins like <a href="https://en.wikipedia.org/wiki/HTTPS_Everywhere">HTTPS-Everywhere</a> installed.</p><p>What the attacker could do now is to make requests to your real website over HTTPS (since you don’t serve without TLS, remember?) and forward it to the user over HTTP. Many users would see no difference as the served HTML and Javascript would be the same and only the <a href="https://-prefix/">https:/</a>/ in the URI would be missing. This way the attacker can easily read the communication between the user and the real server. But he could even go a step further and alter the served website in any way he wants, from inserting subtle advertisement to self-executing malicious scripts. This attack is called <a href="https://en.wikipedia.org/wiki/SSL_stripping#SSL_stripping">SSL-stripping</a>.</p><p>Luckily, web-devs like us can use a header called HSTS (Https Strict Security Policy). It simply forbids the browser to make calls to a known website without SSL/TLS. To enable HSTS, add this to your <em>nginx.conf</em></p><blockquote><strong>Note</strong>: I will add this and other configurations to the SSL-server-block, but you can apply it to both servers by moving them to the surrounding http-block. The Observatory is satisfied as long as the SSL-server is secure.</blockquote><pre>add_header Strict-Transport-Security &quot;max-age=31536000; includeSubdomains&quot;;</pre><p>With max-age set to 12 months (the Observatory wants at least 6) a browser will call your website exclusively over https for one year since its last visit.</p><p>Be aware, HSTS-settings are saved in each of your user’s browsers separately, so if you want to get rid of TLS, you will need to tell your customers <a href="https://www.thesslstore.com/blog/clear-hsts-settings-chrome-firefox/">to clear their browsers HSTS settings</a> or wait for <em>max-age</em>.</p><p>Another thing to keep in mind is that HSTS only works if the user visited your website before. If he is a first-time visitor, an attacker still might strip TLS/SSL by applying redirection before your server can. While this is not required to pass the audit, to prevent this attack, you can preload your website’s HSTS configuration directly into the user’s browsers, provided they support this feature. To do so, submit your HSTS configuration at <a href="https://hstspreload.org/">https://hstspreload.org/</a> and use the preload flag:</p><pre>add_header Strict-Transport-Security &quot;max-age=31536000; includeSubdomains; preload&quot;;</pre><p>Keep in mind, this change is even harder to revert than regular HSTS, so make sure you will be able to provide HTTPS for the duration of <em>max-age</em>. Currently there are around 50.000 domains using this service:</p><p><a href="https://medium.com/bugbountywriteup/find-edges-hsts-preload-list-part-i-2ee5ce6bc5aa">Find Edge’s HSTS Preload List (Part I)</a></p><h4>Referrer-Policy</h4><p>When you click a link to another website, a “Referer” header with the origin URL is usually sent in the request in order to let the destination website know where the user came from.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J2RtYFrnUIrBpMl0qbNSWg.jpeg" /><figcaption>Think of Referer as the sender’s address on a letter.</figcaption></figure><p>The Referer-header is the main source of information for Google Analytics (they do have a few other hacks up their sleeves though, in case it’s missing) and its primary use-case is to help website-owners to optimize their SEO. But it is also sometimes used against “bandwidth-stealing”, allowing requests to resources only to allowed sources, thus preventing embedding images on other websites. But most of the times the Referer is optional and usually URLs on the Internet can be called from the browser’s address-bar without the header being set.</p><p>Now because URLs can contain sensitive information (<a href="http://example.com/do-i-have-hemorrhoids?user=johndoe,"><em>http://example.com/do-i-have-hemorrhoids?user=johndoe</em></a><em>) </em>transmitting it to another website is sometimes problematic, especially over an insecure connection where other entities before the endpoint can read that information as well. To prevent this kind of eavesdropping by a party in the middle, the so-called “Referrer-Policy” was introduced.</p><p><strong>Note</strong>: <em>“Referer” is a misspelling of the word </em>Referrer <em>that</em> <em>found it’s way into the HTTP-standard some time ago. So the browser-set header is officially called Referer but the server-set header controlling/advising the browser is called Refer</em><strong><em>r</em></strong><em>er-Policy</em></p><p>The Referrer-Policy is set by the source website, instructing the browser to strip parts of the URL (if needed) before redirecting to a destination website.</p><p>The good thing about Referrer-Policy is that browsers have a default value when the source website doesn’t specify one explicitly. That default value is “no-referrer-when-downgrade” and it means that Referer is not sent when you go to a HTTP site from a HTTPS one, but all other combinations do send it. E.g:</p><ul><li>HTTP → HTTP</li><li>HTTP → HTTPS,</li><li>HTTPS → HTTPS</li><li>HTTPS ⇢HTTP (no Referer)</li></ul><p>The logic behind it is simple: when going to a HTTP website everybody between the browser and the destination server (e.g. all the men in the middle) can read the traffic and know where the user came from. This is not tragic when coming from an HTTP website, because it is assumed you have nothing to hide anyway if the origin was not secured in the first place. But on a security downgrade this is considered information-leakage.</p><p>There are a few other Referrer-Policy options which you might find useful; you can check them out <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy">here</a>. For example you can make the browser strip the URL parameters only revealing your protocol and domain. Or you can tell the browser not to send any origin at all, if your site is so private that you don’t even trust the possible destination web-servers.</p><p>It is considered good practice to set the header explicitly and the Observatory will give you points for it as it shows you know what you are doing. To pass the audit the default no-referrer-when-downgrade setting is enough:</p><pre>add_header Referrer-Policy no-referrer-when-downgrade;</pre><h4>HPKP</h4><p>In the Observatory you can find a check called HPKP. Https Public Key Pinning was a technique that dealt with the unlikely event of a Certificate Authority becoming compromised and issuing forged certificates. With HPKP the browser could recognize forged certificates from a certain CA after encountering real certificates from the same CA in the past on that website. If the signature appeared forged, the user was presented with a warning, the same as for self-signed certificates.</p><p>HPKP was mostly pushed by Google, but it was a bit hard to implement and the rest of the Internet was reluctant to adopt it. Some even argued that it was a <a href="https://www.thesslstore.com/blog/industry-experts-say-dont-use-key-pinning-hpkp/">bad practice</a>. Finally even <a href="https://www.theregister.co.uk/2017/10/30/google_hpkp/">Google abandoned HPKP in 2017</a>. So while the Observatory still has a HPKP check, it does not add to the audit score and this is why we will skip this one configuration.</p><h4>Other HTTPS improvements</h4><p>There are a few other tricks to improve HTTPS with Nginx which I found in <a href="https://gist.github.com/plentz/6737338">this GitHub-thread</a> (also read the comments!). Since the techniques are out of the scope of this beginner-level tutorial and require a bit more knowledge of cryptography, I will not go into detail about them.</p><p>For now you can just add this code to your SSL-server-block:</p><pre>ssl_session_cache shared:SSL:50m;<br>ssl_session_timeout 1d;<br>ssl_session_tickets off;</pre><pre>ssl_dhparam /etc/ssl/dhparam.pem;</pre><pre>ssl_prefer_server_ciphers on;<br>ssl_protocols TLSv1 TLSv1.1 TLSv1.2;<br>ssl_ciphers &#39;ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS&#39;;</pre><pre>resolver 8.8.8.8 8.8.4.4;<br>ssl_stapling on;<br>ssl_stapling_verify on;<br>ssl_trusted_certificate /etc/ssl/localhost.crt;</pre><blockquote>For the next step you need OpenSSL, a C++ tool that we installed inside the Docker-image in the first part of this tutorial. If you use a Mac you can get more help on OpenSSL in this tutorial: <a href="https://medium.com/@timmykko/using-openssl-library-with-macos-sierra-7807cfd47892">https://medium.com/@timmykko/using-openssl-library-with-macos-sierra-7807cfd47892</a></blockquote><p>Now you have to generate a dhparam.pem which you can do in your Angular project using this command:</p><pre>openssl dhparam -out dhparam.pem 2048</pre><p>As the warning says, it is going to take some time! When finished, make sure it’s copied to the Docker image by adding this to your Dockerfile:</p><pre>COPY dhparam.pem etc/ssl/dhparam.pem</pre><p>Do not worry, as <a href="https://security.stackexchange.com/a/94397/91431">explained here</a> the dhparam.pem can be public and you don’t need to generate it inside the Docker container on every deployment.</p><p>When the docker container is running you should see the warning that ssl-stapling will be ignored (until you move away from self-signed certificates). If something here didn’t work for you, you can find the final code with a generated dhparam.pem <a href="https://github.com/philly-vanilly/angular-nginx/tree/61a4dfe8200888546fcdb95037184d914f8fc73b">here</a>.</p><h4>Summary</h4><p>We successfully strengthened our HTTPS configuration to deal with various Man-In-The-Middle scenarios and increased our audit score. Hooray!</p><h4>Coming up next…</h4><p>The next part of the tutorial will be about Cross-Site-Scripting (one of the most common attacks on the Internet) and its main countermeasure, the Content-Security-Policy. There will also be a few other things checked by the observatory; we will finally get a perfect sore! Don’t miss it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=460c67527dac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical Introduction to Web-Security with Angular and Nginx (Part 1)]]></title>
            <link>https://medium.com/@philip_lysenko/basic-web-security-with-angular-and-nginx-535fa5a2a866?source=rss-4501ab28e9c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/535fa5a2a866</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[web-hosting]]></category>
            <category><![CDATA[web-security]]></category>
            <dc:creator><![CDATA[Philip Lysenko]]></dc:creator>
            <pubDate>Sun, 05 Aug 2018 20:27:01 GMT</pubDate>
            <atom:updated>2018-11-21T07:51:03.631Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qLdzVvaD8vgfiefkD0l5rw.jpeg" /></figure><p>In this tutorial you will learn how to make your website pass a security audit with MDN’s <a href="https://observatory.mozilla.org/">Observatory</a> by setting a few configuration options in Nginx and Angular. Along the way you will learn how to setup Angular in a Docker container and run it on Nginx. For this tutorial no framework- or web-server-specific knowledge is required; we will start from scratch!</p><p>Before setting up a testable environment, let’s take a look at Observatory. If your website is already deployed on the Internet, you can just go to <a href="https://observatory.mozilla.org/">https://observatory.mozilla.org/</a> and make a security audit for your domain. Here is an example Observatory audit for medium.com:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VK8tcF882yWpvzwgiLDr5g.png" /></figure><p>If you are not in production yet, don’t worry — I will show you how to use the offline version of the Observatory, which you can even integrate in a CI-pipeline.</p><h4>Prerequisite: Running Angular from Docker</h4><p>Starting from scratch, we need to install the Angular-Cli globally via NPM and create a new Angular-project (I give it the name <em>angular-nginx</em>). Execute this in the terminal:</p><pre>npm install -g @angular/cli<br>ng new angular-nginx</pre><p>Now you can could simply build the project with ng build —-prod and put the output in Nginx’s html-directory from where it would be served. But to make things a bit more realistic, I want to do all of this in a dockerized container. For this you need to create three files in your Angular project’s root folder:</p><p><em>Dockerfile</em></p><pre># Stage 0, for downloading project’s npm dependencies, building and compiling the app.<br># Angular 6 requires node:8.9+</pre><pre>FROM node:10 as node<br>WORKDIR /app<br>COPY package.json /app/<br>RUN npm install<br>COPY ./ /app/<br>RUN npm run build --prod</pre><pre># Stage 1, for copying the compiled app from the previous step and making it ready for production with Nginx</pre><pre>FROM nginx:alpine<br>COPY --from=node /app/dist/angular-nginx /usr/share/nginx/html<br>COPY nginx.conf /etc/nginx/nginx.conf</pre><p><em>.dockerignore</em></p><pre>node_modules</pre><p><em>nginx.conf</em></p><pre>#user  nginx;<br>worker_processes  1;<br><br>#error_log  logs/error.log;<br>#pid   /run/nginx.pid;<br><br>events {<br>    worker_connections  1024;<br>}<br><br>http {<br>  # Compression<br>  gzip  on;<br>  gzip_http_version 1.1;<br>  gzip_comp_level 2;<br>  gzip_types text/plain text/css<br>                  application/x-javascript text/xml<br>                  application/xml application/xml+rss<br>                  text/javascript;<br>  server {<br>      listen 80;<br>      location / {<br>          root /usr/share/nginx/html;<br>          index index.html index.htm;<br>          try_files $uri $uri/ /index.html =404;<br>      }<br>   }<br>}</pre><p>You can read what these files do in this tutorial if you want to dig in further:</p><p><a href="https://medium.com/@tiangolo/angular-in-docker-with-nginx-supporting-environments-built-with-multi-stage-docker-builds-bb9f1724e984">Angular in Docker with Nginx, supporting configurations / environments, built with multi-stage…</a></p><p>For now it is enough to know that the server {...} -block is the configuration for one server and Nginx can configure multiple servers by surrounding server {...} -blocks inside anhttp {...} -block. The single server in our nginx.conf is only serving a static index.html for now.</p><p>Now you can build your container. If you didn’t do it already, install <a href="https://www.docker.com/">Docker</a> and start the daemon. Then execute this in the terminal:</p><pre>docker build -t angular-nginx .</pre><p>The -t parameter assigns the docker image a tag and the . at the end specifies a location of the Dockerfile. Now run the built image:</p><pre>docker run -p 80:80 -it angular-nginx</pre><p>The -p parameter sets a port-mapping and -it makes the running container interactive, so you can jump inside from your console for debugging. Note that you can exit an interactive terminal session with Control+C. The last parameter in the command is the name of the image which we have built before. Now if you open your browser on <a href="http://localhost/">http://localhost:80</a> you should see this default Angular-page, served from NGINX in Docker:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*DnMaDdGCmfexWZwQcJxmLA.png" /></figure><h4>Prerequisite: Running the audit locally</h4><p>Unfortunately you cannot run the Observatory <em>Web</em>-audit on a website hosted on your private network. You can, however, download the <a href="https://github.com/mozilla/http-observatory">Observatory-CLI</a> and run that on your localhost-server with Python 3:</p><pre>git clone https://github.com/mozilla/http-observatory.git<br>cd http-observatory<br>pip3 install --upgrade .<br>pip3 install --upgrade -r requirements.txt</pre><p>If you run into an error with some PostgreSQL-package like me, check out this <a href="https://stackoverflow.com/questions/11618898/pg-config-executable-not-found">thread on stack overflow</a>. For me it helped to install that one package manually. After installing everything you can run the check:</p><pre>httpobs-local-scan --http-port 80 --no-verify localhost</pre><p>It should print <a href="https://gist.github.com/philly-vanilly/77f6ed4a839e0391812185c724180a50">something like this</a> in your console, telling you that these checks fail:</p><ul><li>HTTPS (-redirection)</li><li>HPKP</li><li>HSTS</li><li>CSP</li><li>Referer Policy</li><li>SRI</li><li>x-content-type-options</li><li>x-frame-options</li><li>x-xss-protection</li></ul><p>As you can see from their attribution to the overall FAIL score, some of them are considered more and some less critical. I will go through the checks one by one, starting with the HTTPS-related ones as they are the most important.</p><h4>HTTPS</h4><p>HTTPS is the basis of security on the Internet. It protects against one of the most common kind of attacks on the Internet, the Man In The Middle (MITM) attack. In MITM, an attacker places himself between two communicating parties (for example the user and a bank-server), thus gaining the ability to read and possibly alter the communication between them. With HTTPS the communication between those two parties is encrypted on the SSL/TLS layer of the OSGI model (e.g. below the application layer and thus hardware-optimised and fast). This way possible attackers sitting in between the communicating parties (like bad WiFi hosts) can only read encrypted messages which they cannot understand or alter, unless they break the encryption or gain access to cryptographic secrets.</p><p>You can read more about public-key cryptography on <a href="https://en.wikipedia.org/wiki/Public-key_cryptography">Wikipedia</a>. For now you just need to know that each communication party needs a pair of private/public keys for establishing a secure connection. Normally a publicly trusted third party called <a href="https://en.wikipedia.org/wiki/Public-key_cryptography#Certification_authority">certification authority</a> would generate those keys. For our testing environment we will impersonate that certification authority and use self-signed certificates.</p><p><strong><em>Warning</em></strong><em>: As you can see HTTPS is pretty important. The following configuration is intended for testing purposes only. In production you should use a service like </em><a href="https://letsencrypt.org/"><em>Let’s Encrypt</em></a><em> instead of self-signed certificates. And depending on your architecture you might even consider doing encryption and redirection on a load-balancer like F5 or some external service instead of the web-server. This way you would have only one entry-point to manage and keep secure.</em></p><p>You might have noticed, our Dockerfile uses Alpine Linux as the base-image. Alpine Linux has a primer on security and ships only with the basic packages needed for running a server in production. So for creating cryptographic keys ourselves (which you should not do in production), you need to install two additional packages. Add this at the end of your Dockerfile:</p><pre>RUN apk update<br>RUN apk upgrade<br>RUN apk add bash<br>RUN apk add openssl<br>RUN /bin/bash -c &quot;openssl req -x509 -out etc/ssl/localhost.crt -keyout etc/ssl/localhost.key \<br>      -newkey rsa:2048 -nodes -sha256 \<br>      -subj &#39;/CN=localhost&#39; -extensions EXT -config &lt;( \<br>       printf &#39;[dn]\nCN=localhost\n[req]\ndistinguished_name = dn\n[EXT]\nsubjectAltName=DNS:localhost\nkeyUsage=digitalSignature\nextendedKeyUsage=serverAuth&#39;)&quot;</pre><p>Now Docker installs bash and openssl and generates the private <em>localhost.key</em> and the public <em>localhost.crt </em>(.crt for public certificate). If you want, you can check that everything worked correctly by building the image and running it with the -it parameter like I have shown you above; after navigating to /etc/ssl, you should see both key-files.</p><p>Now we want to create two web-servers: one for all the calls asking for not-secure and one for secure connections. For passing the Observatory audit, the server for non-secure connections should never serve the website and always redirect to the secure server using TLS. To create both servers, replace the one existing server {...}-block in the nginx.conf with these two:</p><pre>server {<br>    listen 80;<br><br>    server_name localhost;<br><br>    return 301 https://$server_name$request_uri;<br>}<br><br>server {<br>    listen 443 ssl;<br><br>    ssl_certificate /etc/ssl/localhost.crt;<br>    ssl_certificate_key /etc/ssl/localhost.key;<br><br>    server_name localhost;<br><br>    location / {<br>        root /usr/share/nginx/html;<br>        index index.html index.htm;<br>        try_files $uri $uri/ /index.html =404;<br>    }<br>}</pre><p>Now we have one server listening on port :80 and responding with a redirect-status-code 301, telling the browser to try the same address with the <a href="https://-prefix/"><em>https://</em>-prefix</a>. And we have the server which the unsecured one points to, listening on port :443. It is the default port for communication over SSL/TLS and https-calls automatically resolve to it. Now after rebuilding the docker-image you have to run it exposing the second port too:</p><pre>docker run -p 80:80 -p 443:443 -it angular-nginx</pre><p>When you call http://localhost:80 in the browser, you should be automatically redirected to <a href="http://localhost/">https://localhost</a> and prompted with a warning like this because you use self-signed certificates, which do not have a signature of a publicly-known and trusted certificate authority:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X4yZuONR0Zt3sGx18ZS30g.png" /></figure><p>If you click on <em>proceed</em> you should connect to your web-server over TLS now, although your browser will still probably mark the website as insecure in the address bar.</p><p>If you run the <a href="https://gist.github.com/philly-vanilly/77f6ed4a839e0391812185c724180a50">audit</a> now, it should not complain about missing HTTPS and redirection anymore.</p><h4>Bonus: Hiding Server Version</h4><p>If you inspect the audit in detail, you might notice this line:</p><pre>“Server”: “nginx/1.13.12”,</pre><p>As you can see, this simple scan that anyone could execute on a public website shows the server’s internals (lib and version number). With this information attackers can simply look up vulnerabilities of that specific configuration. So while this is not affecting the Observatory’s score, one thing you definitely should set in your nginx.conf for production is this (add it to the http-block):</p><pre>server_tokens off;</pre><p>This prevents Nginx from submitting tokens with version information. After running the audit again, the Server-field will only show that you are running nginx and attackers would need to do a more in depth search to find clues what version you are using.</p><blockquote><strong>Off-topic</strong>: You might have heard the phrase “no security by obscurity”, which means hiding a broken lock is not as good as fixing the lock. But while obscurity shouldn’t replace fixing, it is valid for obscurity to be an addition to a functioning system.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zu0m6dtGj7-Zz2jCNe7BSw.jpeg" /><figcaption>Would you use it to lock your stuff?</figcaption></figure><h4>End of Part 1</h4><p>That’s it for the first part! Here you can see all the project files as a repo: <a href="https://github.com/philly-vanilly/angular-nginx/tree/fbf04e9acdc60da57d4d24d9b748bea091a123e7">https://github.com/philly-vanilly/angular-nginx/tree/fbf04e9acdc60da57d4d24d9b748bea091a123e7</a></p><h4>Coming up next…</h4><p>In the second part of this tutorial we will strengthen our HTTPS settings and in the third part we will take a look at Cross-Site-Scripting attacks and their countermeasures. Don’t miss it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=535fa5a2a866" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>