<?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 David Silva on Medium]]></title>
        <description><![CDATA[Stories by David Silva on Medium]]></description>
        <link>https://medium.com/@david-silva?source=rss-38a90728851a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qUXtOVZao9UTxLoRrhQSYQ.jpeg</url>
            <title>Stories by David Silva on Medium</title>
            <link>https://medium.com/@david-silva?source=rss-38a90728851a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 00:34:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@david-silva/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[How to implement csrf protection on a JWT-based app (Node, csurf , Angular)]]></title>
            <link>https://david-silva.medium.com/how-to-implement-csrf-protection-on-a-jwt-based-app-node-csurf-angular-bb90af2a9efd?source=rss-38a90728851a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb90af2a9efd</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[csrf]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[David Silva]]></dc:creator>
            <pubDate>Sun, 14 Apr 2019 11:59:19 GMT</pubDate>
            <atom:updated>2021-07-19T05:49:49.087Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to implement CSRF protection on a JWT-based app (Node, csurf , Angular)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iS4PH4Gt34jy61SmXKgBWw.png" /></figure><p>I have been developing an application in Node.js and Angular that uses JWT for authentication and authorization. The authentication token is stored as an HTTP-only cookie on the client’s browser. This simplifies the front-end application code, as it doesn’t have to keep track of the token (cookies are automatically sent by the browser on each request).</p><p>However, using cookies for the authentication makes the application vulnerable to CSRF attacks. There are excellent resources online to learn more about CSRF, like <a href="https://en.wikipedia.org/wiki/Cross-site_request_forgery">Wikipedia </a>and the <a href="https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)">OWASP page</a>. Let’s find out how such an attack can happen and how to mitigate the vulnerability.</p><h3>The problem</h3><p>A CSRF attack against a website that uses cookies for authentication (say <em>app.com</em>) could be performed in the following way:</p><ul><li>The user accesses a malicious website, <em>evil.com</em>, with his browser.</li><li>The malicious page contains a hidden request to the victim site, <em>app.com</em>. It could be, for example, a hidden form that posts some content to the <em>/api/transfer_money</em> endpoint.</li><li>The browser automatically attaches all the cookies that it has for the <em>app.com</em> domain. The authentication cookie is attached to the request.</li><li>From the server’s point of view, this is a legitimate request, because it contains the authentication cookie. The POST action is successful.</li><li>As a result, the attacker can perform actions on behalf of the user. However, the attacker’s code can’t read server responses, due to <a href="https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy">same-origin policy</a>.</li></ul><h3>The solution</h3><p>We need to set an extra value — token — that can be passed to the server to verify the request’s authenticity.</p><ul><li>When the user navigates for the first time to the website,<em> app.com</em>, the server sets a CSRF cookie.</li><li>This cookie is only readable by the JavaScript code on the <em>app.com</em> domain.</li><li>The cookie needs to be sent back to the server in two different ways: as a cookie, and as a header. Adding it as a header is the frontend application’s responsibility, and guarantees that the request is genuine: no external code could have set it.</li></ul><p>The <em>csurf </em>library works a bit differently, let’s have a look at it next.</p><h3>Server-side: the csurf library</h3><p>Many projects use the <a href="https://github.com/expressjs/csurf"><em>csurf</em></a> library on the server side to add mitigation against CSRF attacks. It is a great library, but I have found that the way it works is often misunderstood by developers.</p><p>Let’s see how this library should be used. We are going to use <em>csurf </em>with the “cookie” option set to true, without a session middleware.</p><p>First, let’s have a look at an example back-end code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0de67c255b1cc8d0d9928ada81dd5b96/href">https://medium.com/media/0de67c255b1cc8d0d9928ada81dd5b96/href</a></iframe><p>As you can see, our application includes 4 endpoints:</p><ul><li>The landing page (<em>/</em>)</li><li><em>/login: </em>receives the username and password combination and validates them against the database. As you can see, we have omitted this process and we are simply sending back the authentication cookie, as if the user was successfully logged in.</li><li><em>/api/stats</em>: a GET endpoint that returns some data.</li><li><em>/api/transfer_money</em>: a POST endpoint that executes an action for the user. In this case, it transfers some money to a different account.</li></ul><p>We have also greatly simplified the authentication checks. I decided to keep those details out of this example. Let’s find out how <em>csurf </em>works in detail.</p><h4>Client — server communication</h4><p>On a first GET request, the server sends the client two cookies, with the names of _csrf and XSRF-TOKEN:</p><ul><li>_csrf is generated automatically because we chose to set { cookie: true }. This is a secret, not the CSRF token. The server uses this secret to match the actual token against it. The _csrf cookie is an alternative to using sessions: instead of storing the secret on the server, tied to a user session, we store it on the client’s browser as a cookie.</li><li>XSRF-TOKEN is the CSRF token. We need to generate it manually with the function req.csrfToken(). It needs to be sent to the client on the first request. This can be done in multiple ways; our example project sets it as a cookie. The client needs to send it back either in the body, query string, or headers of every mutating request (see the <a href="https://github.com/expressjs/csurf#value">docs</a>).</li></ul><p>For every following GET request:</p><ul><li>CSRF protection is not necessary.</li><li>We shouldn’t use the csrfProtection middleware on the server code, for any GET endpoint other than / .</li></ul><p>For every following POST/PATCH/PUT/DELETE request:</p><ul><li>We must use the csrfProtection middleware on the server code.</li><li>The server will check the _csrf cookie sent by the client against the value of XSRF-TOKEN, sent also by the client, in the request body, query string, or headers.</li></ul><h4>Other things to consider</h4><ul><li>The XSRF-TOKEN will probably be sent back by the client as a cookie (because of the way cookies work), but the server will ignore it, as it will look for it only in the request body/query string/headers.</li><li>The code that generates the token (res.cookie(&#39;XSRF-TOKEN&#39;, req.csrfToken())) should only be run once, when we first GET the root page /.</li><li>The _csrf secret is generated by the server (and sent as a ‘set-cookie’) every time the client sends a request fulfilling the following conditions: (1) It doesn’t include the _csrf cookie, and (2) it hits a route that uses the csrfProtection middleware.</li><li>When using the csrfProtection on a GET route in the server code, the server will ignore any CSRF check. However, the server will generate and set a new secret cookie, _csrf, if the client didn’t send it.</li></ul><p>This setup will provide us with CSRF protection if the client-side is configured properly</p><h3>Client-side: Angular</h3><p>Fortunately for us, Angular has <a href="https://angular.io/guide/http#security-xsrf-protection">built-in CSRF protection mechanisms</a>. All we have to do is adding the following lines to our AppModule:</p><pre>imports: [<br>  HttpClientModule,<br>  HttpClientXsrfModule.withOptions({<br>    cookieName: &#39;XSRF-TOKEN&#39;,<br>    headerName: &#39;X-XSRF-TOKEN&#39;,<br>  }),<br>],</pre><p>The Angular app will then automatically intercept the XSRF-TOKEN cookie and send it back as a header, named X-XSRF-TOKEN , on every mutating request.</p><p>Check this story and more at my blog <a href="https://cybertricks.blog/">cybertricks.blog</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb90af2a9efd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular — Unit testing Upload Progress HTTP events]]></title>
            <link>https://david-silva.medium.com/angular-unit-testing-upload-progress-http-events-48135e16f9f4?source=rss-38a90728851a------2</link>
            <guid isPermaLink="false">https://medium.com/p/48135e16f9f4</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[file-upload]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[jasmine]]></category>
            <dc:creator><![CDATA[David Silva]]></dc:creator>
            <pubDate>Wed, 27 Mar 2019 18:43:50 GMT</pubDate>
            <atom:updated>2021-07-10T18:14:48.069Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular — Unit testing Upload Progress HTTP events</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lRxHIeTWmlSvXWJtNC-EwQ.jpeg" /></figure><p>I have been developing an Angular web application that includes a multi-file upload input. The service that is in charge of the upload streams a series of progress events to its clients, so they are informed of the upload progress percentage.</p><p>The upload progress is reported via an HttpEvent, which is different from a normal HTTP response. There seems to be very little information out there on how to unit test these events, so I’m going to share with you two ways in which this can be achieved.</p><h3>The theory</h3><p>I recommend you to read <a href="https://www.dotnetcurry.com/angularjs/1448/angular-http-client-interceptors-headers-event">this excellent article</a> for a deep dive on Angular’s HttpClient. Quoting it:</p><blockquote>… if we need an even better control and need to access individual events or steps while making a HTTP call, observe HttpEvent. It works at a much lower level. It exposes events that capture progress of both the request and response.</blockquote><p>So, it looks like <a href="https://angular.io/api/common/http/HttpEvent">HttpEvent </a>is a general class that includes <a href="https://angular.io/api/common/http/HttpResponse">HttpResponse</a>, <a href="https://angular.io/api/common/http/HttpProgressEvent#type">HttpProgressEvent </a>and others. The documentation (linked on the names) makes clear the relationship between them: HttpEvent is a “union type for all possible events on the response stream.”</p><p>On the other hand, Angular’s<a href="https://angular.io/api/common/http/HttpClient#request"> HttpClient.request() </a>returns a stream of HttpEvents when we pass it an instance of a HttpRequest. Let’s see how we can mock these response events to use them in our unit tests.</p><h3>The setup</h3><p>A typical Angular file upload service with an upload function that informs its subscribers of the progress can look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8eec7d19d3ec671598b23a1e3a336b7d/href">https://medium.com/media/8eec7d19d3ec671598b23a1e3a336b7d/href</a></iframe><p>As you can see, we listen for any type of event that comes from the HttpClient request. If that event happens to be of the type UploadProgress, we broadcast the new value to the subscribers. If it is a HttpResponse, then we report a progress of 100 and we complete the observable.</p><h3>Naive approach: just mock HttpClient</h3><p>The first thing that came into my mind was to create a mock HttpClient object that includes only the request function. Then, we can create a Jasmine spy for that function and return whatever we want. And it works! In the end of the day, we only need to return an object with a specific type: <a href="https://angular.io/api/common/http/HttpProgressEvent#type">HttpProgressEvent</a>. The documentation tells us what properties to include.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ce58e221d1e49158c21b59bd870c1fc/href">https://medium.com/media/3ce58e221d1e49158c21b59bd870c1fc/href</a></iframe><h3>Use the HttpClientTestingModule</h3><p>After digging a bit deeper, I found out that the <a href="https://angular.io/api/common/http/testing/TestRequest">TestRequest</a> class, which we use when we want to <a href="https://angular.io/guide/http#testing-http-requests">test a standard HTTP request</a> with the HttpClientTestingModule, has an .event() method that does exactly what we need! From the documentation:</p><blockquote>Deliver an arbitrary HttpEvent (such as a progress event) on the response stream for this request.</blockquote><p>Using that method, our test looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51f44314ec4a151b9ca366f94e222934/href">https://medium.com/media/51f44314ec4a151b9ca366f94e222934/href</a></iframe><p>That’s all I wanted to share on this article, if it has been useful please give it a clap!</p><p>For more articles like this one, visit <a href="https://cybertricks.blog/">my personal blog cybertricks.blog!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48135e16f9f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>