<?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 Marcos De Aguiar on Medium]]></title>
        <description><![CDATA[Stories by Marcos De Aguiar on Medium]]></description>
        <link>https://medium.com/@marcos.deaguiar?source=rss-19f96fb190e4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*mCCzOvPfqK8ZqlR2PyOVkw.jpeg</url>
            <title>Stories by Marcos De Aguiar on Medium</title>
            <link>https://medium.com/@marcos.deaguiar?source=rss-19f96fb190e4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 13:53:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@marcos.deaguiar/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[Start TypeORM project with Database Offline]]></title>
            <link>https://medium.com/@marcos.deaguiar/start-typeorm-project-with-database-offline-ccb8cb7ac397?source=rss-19f96fb190e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccb8cb7ac397</guid>
            <category><![CDATA[typeorm]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Marcos De Aguiar]]></dc:creator>
            <pubDate>Thu, 26 Nov 2020 18:34:08 GMT</pubDate>
            <atom:updated>2020-11-26T18:34:08.647Z</atom:updated>
            <content:encoded><![CDATA[<p>I was always a big fan of ORM frameworks, they help us deal with application data at a higher level and abstract away the tedious persistence part. Some may criticize the performance of ORM’s, but IMHO if you’re using it to insert and update only, it’s already a big win, you can always plug in your optimized queries later on.</p><p>I already had good experiences with Hibernate, nHibernate and Entity Framework. When I started out to code in Node.js/Express, I started to look for a good ORM for this platform as well. Since I’m coding with Typescript, TypeORM with the DataMapper pattern appealed to me best.</p><p><strong>Problem:</strong></p><p>When I started to see some code samples for TypeORM, one thing called my attention. In most of these samples, the code was trying to open a connection, and then passing the connection object to the controllers, services etc., as seen in the code below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b27e87594edaeb573daca38618b352c/href">https://medium.com/media/0b27e87594edaeb573daca38618b352c/href</a></iframe><p>But what happens when the database server is not online, and you still need to deploy and start your web server? This is not an issue with Entity Framework for example.</p><p><strong>The solution:</strong></p><p>Ideally I would like to have the Repositories injected as dependencies in my services, but repositories can only be retrieved after a successful connection is established. Interesting enough, if the database goes offline, and then online again, there is no issue with the repositories. They just stop and start working accordingly.</p><p>In Nest.js they have this well solved, because they use a factory method for the connection, and injects the repositories on the fly. But since I’m using Express, I had to come up with another solution.</p><p>I created a file that keeps trying to connect to the database, until it connects once, then it breaks out of the loop. If the connection fails, it just waits 1 second and tries again. Once the connection is made, there is nothing to worry about if it drops later or not. The repositories just recover without any issue as far as I tested.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7f561c8b6a813805a8ec881eb47ed70/href">https://medium.com/media/e7f561c8b6a813805a8ec881eb47ed70/href</a></iframe><p>For the app starting code, just call the method and let it loop until it connects.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42db648a40ff63b7e55a0224f9ea2cfd/href">https://medium.com/media/42db648a40ff63b7e55a0224f9ea2cfd/href</a></iframe><p>For the services that need the repository, just make kind of a factory method, that checks if the repository was created already, if not, creates and cache it. If it was already created, it just returns the cached instance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c90666be0c7548b32a0def2f6b0f5718/href">https://medium.com/media/c90666be0c7548b32a0def2f6b0f5718/href</a></iframe><p>As we can see, the downside is that the repos are not constructor injected in the services that use them, which can get in the way of testing. But I’m willing to do this trade off, since the repositories are straighout database access in TypeORM, and it also would be a big pain to mock it given the sheer number of chained methods it uses, so I would go straight to integration testing with it.</p><p><strong>Conclusion:</strong></p><p>In the end, this is just a work around, I don’t know if it’s like this by design or not. I would like to see the thoughts of TypeORM’s team about this issue, and if they intend to implement some kind of lazy connection creation, that let us create repositories even if the database is not online at the moment. The main use case for this, is that Node.js is a stand alone process, and it’s not guaranteed that the database will be accessible when we’re deploying it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccb8cb7ac397" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SPA with cookie authentication in Asp.net Core]]></title>
            <link>https://medium.com/@marcos.deaguiar/spa-with-cookie-authentication-in-asp-net-core-c7ba6d9f8ebe?source=rss-19f96fb190e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7ba6d9f8ebe</guid>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[jwt-token]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <dc:creator><![CDATA[Marcos De Aguiar]]></dc:creator>
            <pubDate>Wed, 20 May 2020 18:41:17 GMT</pubDate>
            <atom:updated>2020-05-20T18:41:17.652Z</atom:updated>
            <content:encoded><![CDATA[<p>Asp.net core is a great framework for web applications, and a big improvement in architecture design in comparison to the Asp.net MVC. But when I started to work with it, I quickly realized that it’s very opinionated about the way some things should be. These opinions are also reflected on the many tutorials and blog posts about the framework.</p><p>If you want to do things a bit differently, you’re kind of out of luck getting help. One of those opinions, even though not explicit, is to use Authorization header token authentication, such as JWT for Single Page Applications (SPA). I personally had a hard time finding a tutorial or documentation that described how to do a SPA with cookie authentication in Asp.net core.</p><p>I won’t dive into the debate whether this is a good idea or not, there are many blog posts and videos about this discussion already. What I’ll do in this article is to present how I was able to implement cookie authentication in SPA using Asp.net core SPA template, and the gotchas I found along the way. It’s also a great opportunity to hack a little bit and see how some internal parts of the framework works.</p><p><strong>The Design:</strong></p><p>When I started to develop software, authentication and authorization were always a big topic of discussion. The main point is that there is not a one size fit all solution, and the strategy hangs on the requirements of the application.</p><p>The design I’ll present in this article is particular to this application and doesn’t mean it’s the best or a silver bullet solution.</p><p>There are a couple of ways to go about this. One is to scrap everything and do your own middlewares and filters, and do all this code. Another is to try to use what the framework offers as much as possible, customizing only the relevant parts. I’m taking the later approach.</p><p>The concept is quite simple, when the user authenticates, I create a JWT token and send it as “Http Only” cookie, so XSS scripts cannot capture it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/793e6963581102a3ca2f0b5044f361a2/href">https://medium.com/media/793e6963581102a3ca2f0b5044f361a2/href</a></iframe><p>I’ll not present how to create the claims and generate the JWT cookie since there are many tutorials about it online. The main point is that the JWT is being returned as a “Http Only” cookie and not for the client application to control directly.</p><p>For the authentication scheme we use the cookie authentication instead of the standard JWT authentication.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15522b36579f04c2359980b14bd44ca4/href">https://medium.com/media/15522b36579f04c2359980b14bd44ca4/href</a></iframe><p>And now is the part where Asp.net core has an opinion on it. I didn’t find a ready to use solution to decode the JWT in a cookie, only the default that decodes it in the header. So I created a custom middleware that all it does is to check if the JWT is still valid and fills the HttpContext User (ClaimsPrincipal) with the data in the JWT.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/908ad0adf2de88fc7541f62751999c31/href">https://medium.com/media/908ad0adf2de88fc7541f62751999c31/href</a></iframe><p><strong>CSRF Protection:</strong></p><p>As expected with this authentication cookie approach, it brings the Cross Site Request Forgery (CSRF) threat. And that’s where another gotcha is in Asp.net core framework. The CSRF protection has 2 elements. A “Http Only” cookie with the CSRF token that stays for the session, and a request token that must be sent together on the request, either in the form body, or in a header. When using the MVC approach, it’s easier to just put the token as a hidden field in the form, but in SPA, normally the POST requests are sent in json format so the CSRF request token must be provided in the header.</p><p>The gotcha here is, that the CSRF request token is calculated taking into consideration the CSRF cookie and the claims in the HttpContext User ClaimsPrincipal. If any claim is different for the CSRF request token, it won’t work. This is one of the reasons we remove the “iat”, “exp” and “nbf” from the claims when setting the ClaimsPrincipal, because if we refresh (not covered in this article) the token, we don’t have to re generate the CSRF request token, or have it fail in the current request.</p><p>So in a SPA everytime the user authenticates a new request token must be passed back to the client via a cookie that is not “Http Only”, so the client can access it and put on the header. When the user logs out, the CSRF request to the anonymous user must be sent back to the client as well. We can see this in the logout listing below.</p><p>As we can see in the middleware code, when the JWT token expires, we send back a CSRF request token for the anonymous user (as with the logout action), so the client can work again with the login endpoint and so on.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e15868b72b25a8fa7809b1404a85328/href">https://medium.com/media/1e15868b72b25a8fa7809b1404a85328/href</a></iframe><p><strong>CSRF for unsecure actions:</strong></p><p>Everything works fine now, but there is one scenario that this approach may generate an unexpected error. If the user is authenticated, and makes a POST for an action that doesn’t require authentication, and the token is expired. That request will fail because the token sent is for a certain user (specific set of claims), and now the anonymous user is the one in the ClaimsPrincipal. Note that because the middleware updates the cookie when the JWT token expires, the next request will work.</p><p>But is that the only way to get around it? Well, there are others. One is not to require CSRF protection to this endpoint anyway. In your application design, any insecure action should not make any changes that will use the user authentication. That being done, there is no gain for someone to trick your user with a CSRF malicious page, because they can do it themselves.</p><p>And this is a big question in general whether to use CSRF for any action that doesn’t require authentication. The login page for instance, wouldn’t necessarily need CSRF since the user is not authenticated anyway.</p><p>But in my approach I do use CSRF in unsecure actions just to be on the safe side, especially on the login page. So in order to have the CSRF token when the user loads your SPA, you also need a middleware to send this request token, as shown in the listing below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a76553bc34760db5375e418400172cc/href">https://medium.com/media/6a76553bc34760db5375e418400172cc/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f57e0bf11b059ef7353c8e147115a1a0/href">https://medium.com/media/f57e0bf11b059ef7353c8e147115a1a0/href</a></iframe><p>This middleware should seat just before the app.UseSpa() middleware, because the the request passes through the previous middlewares, it’s because it didn’t match any file or action, so this UseSpa middleware will send your Index.html with the SPA code to be loaded to the user. The JWT Cookie middleware should be used where you would normally use the Asp.net core default authentication middleware.</p><p><strong>Conclusions:</strong></p><p>As we can see, it’s not a whole lot of code to make it work. But researching the information and putting it together took longer than I thought, specially in the part that says that the CSRF request token is checked based on the claims set in the HttpContext User.</p><p>What is presented here is not the complete solution of course, but the building blocks for someone who wants to create a custom authentication solution in Asp.net core.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7ba6d9f8ebe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom React hook for pagination]]></title>
            <link>https://medium.com/@marcos.deaguiar/custom-react-hook-for-pagination-81d55d5b1e75?source=rss-19f96fb190e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/81d55d5b1e75</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[typescript-with-react]]></category>
            <dc:creator><![CDATA[Marcos De Aguiar]]></dc:creator>
            <pubDate>Sun, 08 Mar 2020 13:08:43 GMT</pubDate>
            <atom:updated>2020-03-08T13:10:06.628Z</atom:updated>
            <content:encoded><![CDATA[<p>React version 16.8 introduced the concept of hooks, and it became the recommended way of writing components that are pure functions but also hold state on it. It comes with the defaults <strong>useState</strong> and <strong>useEffect</strong> hooks, and libraries like redux also adopted it, with the <strong>useSelector</strong> and <strong>useDispatch</strong> hooks.</p><p>We can also develop our own custom hooks to reuse logic and patterns on our application. This article presents a custom pagination hook, that takes in a list and returns values and functions to manipulate a list using pages.</p><p>The full Typescript code is available at: <a href="https://github.com/marcosdeaguiar/react-pagination">https://github.com/marcosdeaguiar/react-pagination</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/400f81dcc25fbac50ddf0c1b1dd0a055/href">https://medium.com/media/400f81dcc25fbac50ddf0c1b1dd0a055/href</a></iframe><ul><li>isPaginating: Boolean value that is set to true if the number of items in the list exceeds the total items per page. It’s useful to hide (or not render) paginator components (as can be seen in the example).</li><li>currentPage: The number of the page that is currently selected.</li><li>setCurrentPage: Function that receives the number of the page. When this function is called, currentPage is updated to the selected page, and the pageItems list is also updated with the data belonging to the selected page.</li><li>pageItems: List of the items belonging to the page. It is the data that will be shown in the page.</li><li>setItemList: Function that is used to update the list that is being paged. The complete list is set on this function, and only a “page” of this list is available on the pageItems.</li><li>totalPages: Total number of pages so this information can be displayed to the user.</li></ul><p>These functions and variables can be assigned to a paginator component for example.</p><p>The paginator component source code is also available at the github repository.</p><p>The following listing shows the source code for the hook:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a71d5228295f4c4507225309fa700090/href">https://medium.com/media/a71d5228295f4c4507225309fa700090/href</a></iframe><p>As we can see, this custom hook is nothing more than a collection of existing hooks.</p><p>The items state hook is the complete list set by the user to be paged. The pageItems is the list filtered to only contains items belonging to the currently selected page.</p><p>A setItemList function was created to set the current page to 1 when a new list is set by the user.</p><p>The rest of the code is straightforward and all it does is to check the total number of pages, items per page, selected page and filter the items to the page items list. If the user sets a page that doesn’t exist, the page items list just becomes empty.</p><p><strong>Conclusion</strong></p><p>This article presented an example of how to build a custom hook out of a composition of existing hooks. It presented a common recurring problem that most web developers face, that is paginating items for the user. Feel free to copy and improve the code on your own projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81d55d5b1e75" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>