<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Andrea Roveroni</title>
    <description>The latest articles on DEV Community by Andrea Roveroni (@roveroniandrea).</description>
    <link>https://dev.to/roveroniandrea</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1366647%2F4f906b72-02d7-47de-9997-adc00d6b708b.jpeg</url>
      <title>DEV Community: Andrea Roveroni</title>
      <link>https://dev.to/roveroniandrea</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/roveroniandrea"/>
    <language>en</language>
    <item>
      <title>What are tokens and cookies in web authentication. Webauth Wizardry pt 1</title>
      <dc:creator>Andrea Roveroni</dc:creator>
      <pubDate>Mon, 25 Mar 2024 16:58:16 +0000</pubDate>
      <link>https://dev.to/roveroniandrea/what-are-tokens-and-cookies-in-web-authentication-webauth-wizardry-pt-1-43h3</link>
      <guid>https://dev.to/roveroniandrea/what-are-tokens-and-cookies-in-web-authentication-webauth-wizardry-pt-1-43h3</guid>
      <description>&lt;h2&gt;
  
  
  Why this post
&lt;/h2&gt;

&lt;p&gt;Searching for answers when dealing with web authentication can be challenging.&lt;/p&gt;

&lt;p&gt;I researched this topic some time ago, and one thing I noticed is that there are a lot of useful resources and informations, but they're spread across Stackoverflow answers, blog posts, online documentation, Reddit posts, and so on.&lt;/p&gt;

&lt;p&gt;Some posts compare bearer token VS cookies, some other explain how cookies might be more secure than tokens, some others go into session authentication, others deal with cookie attributes and CORS and so on. This requires you to jump from page to page and might lead to lose some useful informations regarding security practices or caveats, just because you did not read that Stackoverflow answer that for some reason is not marked as the correct one!&lt;/p&gt;

&lt;p&gt;What I think is missing is a guide that starts from the beginning, explains what are cookies and what are their pros, while also  considering some cons and difficulties when implementing them (CORS? Third party cookies? Partitioned what?).&lt;/p&gt;

&lt;p&gt;So this is the first post of a serie that I called &lt;strong&gt;"Webauth Wizardry"&lt;/strong&gt;, that I hope will help other developers to understand and build a system that provides authentication via http cookies.&lt;br&gt;
In general, I'll try to explain things as I went throught them, by trying solutions and finding which one has the most advantages (at least in my opinion), and to note down what disadvantages you might have with cookies, and eventually some solutions.&lt;/p&gt;

&lt;p&gt;This serie will cover the following topics:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Brief comparison of bearer token VS cookie auth&lt;/li&gt;
&lt;li&gt;Cookie fundamentals: lifetime, attributes, sending rules&lt;/li&gt;
&lt;li&gt;Basic web authentication: how to authenticate users and keep them authenticated&lt;/li&gt;
&lt;li&gt;Sign in with email/pw: I'll start with a brief explanation, but this topic might be expanded later&lt;/li&gt;
&lt;li&gt;Sign in with OpenID Connect: Build on top of Oauth2, OIDC allows an application to authenticate users via third party services (called providers) like Sign in with Google. This topic has some key consideration and caveats, especially regarding requests coming from different origin and some difficulties that will happen when managing our cookies&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  "I like your funny words magic man"
&lt;/h3&gt;

&lt;p&gt;Since we're programmers and we like code, I published two repository on my Github account:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The finished &lt;a href="https://github.com/roveroniandrea/webauth-wizardry"&gt;Webauth Wizardry&lt;/a&gt; code, consisting in a main part under &lt;code&gt;src&lt;/code&gt; folder, along with a testing setup. I also published this as an &lt;a href="https://www.npmjs.com/package/@roveroniandrea/webauth-wizardry"&gt;npm package&lt;/a&gt;, in case someone wants to reuse it (some work is still needed)&lt;/li&gt;
&lt;li&gt;A &lt;a href="https://github.com/roveroniandrea/webauth-wizardry-fe"&gt;FE application&lt;/a&gt;, something as minimal as possible to demonstrate how to integrate all of this (and also how unobtrusive the cookie solution is on FE)&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  Blue pill or red pill?
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9a0tvjw9359iranzqzt3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9a0tvjw9359iranzqzt3.png" alt="Morpheus' choice" width="800" height="417"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;First thing first, let's state something that is not always clear:&lt;br&gt;
&lt;strong&gt;Tokens and cookies serve different purposes and they're not mutually exclusive&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Questions like "Do I need to use tokens or cookies in my application?" might be misleading:&lt;/p&gt;

&lt;h3&gt;
  
  
  Tokens represent someone
&lt;/h3&gt;

&lt;p&gt;Tokens are strings that represent a user (or an application) in some way. They might be just an identifier that corresponds to some user data saved on DB (like a mapping token =&amp;gt; user), or they might contain that same data themselves as encoded &lt;a href="https://jwt.io/"&gt;JSON web tokens&lt;/a&gt; (jwts). A signin mechanism is applied when the jwt is created (aka issued) to ensure that the token cannot be modified by someone else (or at least, without invalidating the sign and thus invalidating the token).&lt;/p&gt;

&lt;p&gt;Since this token identifies a user and grants him permission to access protected resources, this is called an &lt;code&gt;Access Token&lt;/code&gt; (AT).&lt;/p&gt;

&lt;p&gt;A never expiring AT is not a good idea:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;You want to control if a user is still allowed to access a resource, for example after logout of when banning a user&lt;/li&gt;
&lt;li&gt;Someone stealing your AT might be able to operate on your behalf forever on that application&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For these reasons, an AT is usually short-lived (expiration might be set even after 10 minutes), and is paired with a so-called &lt;code&gt;Refresh Token&lt;/code&gt; (RT).&lt;/p&gt;

&lt;p&gt;Refresh tokens do not directly identify a user, but rather allow to exchange an expired (or expiring) AT with a new one. This operation is called "&lt;code&gt;token refresh&lt;/code&gt;", and when succeded returns both a new AT and a new RT, invalidating the provided ones. This also means that RT are single use only.&lt;/p&gt;

&lt;h3&gt;
  
  
  Access Token might be passed by Authorization Bearer or Cookie
&lt;/h3&gt;

&lt;p&gt;Now we need a way to pass the AT (and RT if needed) back and forth from our BE and FE.&lt;/p&gt;

&lt;p&gt;We can use:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;Authorization: Bearer MY_TOKEN&lt;/code&gt; HTTP header&lt;/li&gt;
&lt;li&gt;Custom cookie&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Which one to use? They both have pros and cons:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Authorization bearer are more flexible than cookies, as that they can be passed without much browser restrictions. Also, they can be set only on request that actually need them. On the other hand, they must be manually handled by the FE, which needs to keep track of both AT and RT, place the AT on the header on every request, handle manually refreshing the token before it expires, and save those tokens somewhere. In addition, since they're available to client side Javascript, they might be stolen by an attacker that manages to execute some custom code on the victim's browser.&lt;/li&gt;
&lt;li&gt;Cookies are more "transparent" to client, meaning that when handled correctly, they cannot be accessed client side, so their entire handling occurs on BE. On the other hand, browsers enforce more strict policies on cookies, they're sent on every request (even if not needed) and they're subsceptible to other forms of attacks, like CSRF. Thus they require a precise configuration to be used correctly for authentication purposes.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Session cookies
&lt;/h3&gt;

&lt;p&gt;The combination of simple (non encoded) tokens and cookies might be called the "session authentication", or "session cookies". This is sometimes confused with simple cookies, but as seen before, cookies does not exclude jwt tokens.&lt;/p&gt;

&lt;p&gt;Session cookies are just cookies containing a token that identifies the user. The user's data is then recovered from the token on the server side, which might store data in-memory or on a fast DB, for example Redis might be a good option.&lt;/p&gt;

&lt;h3&gt;
  
  
  I'll take the red pill
&lt;/h3&gt;

&lt;p&gt;After considering all the possibilities, I choose to go with jwt tokens, to prevent retrieving user info from a db on every request, and cookies instead of Bearer Token, in order to eliminate all possible handling from the FE.&lt;/p&gt;

&lt;p&gt;Let's see how deep does the rabbit hole go.&lt;/p&gt;




&lt;h3&gt;
  
  
  Ending considerations
&lt;/h3&gt;

&lt;p&gt;Feel free to comment for any question, error correction, or just to say hi. Also, you're welcome to visit my Github profile and open some issues or pr!&lt;br&gt;
This is one of my first posts, hope you liked it, and thanks for reading.&lt;/p&gt;

&lt;h3&gt;
  
  
  Other resources (not sponsored :))
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;See this &lt;a href="https://stackoverflow.com/questions/17000835/token-authentication-vs-cookies/35059874#35059874"&gt;Stackoverflow Answer&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Also this &lt;a href="https://stackoverflow.com/questions/76760681/how-to-manage-access-and-refresh-jwts-in-http-only-cookies"&gt;Stackoverflow Question&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Used in this article
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Cover image &lt;a href="https://www.freepik.com/"&gt;designed by Freepik&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Morpheus's choice image generated with &lt;a href="https://imgflip.com/memegenerator"&gt;Imgflip&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>webdev</category>
      <category>cookie</category>
      <category>authentication</category>
    </item>
    <item>
      <title>Playing Bad Apple! by throwing Javascript errors</title>
      <dc:creator>Andrea Roveroni</dc:creator>
      <pubDate>Tue, 19 Mar 2024 20:44:21 +0000</pubDate>
      <link>https://dev.to/roveroniandrea/playing-bad-apple-by-throwing-javascript-errors-ip1</link>
      <guid>https://dev.to/roveroniandrea/playing-bad-apple-by-throwing-javascript-errors-ip1</guid>
      <description>&lt;p&gt;Inspired by all those beautiful videos playing Bad Apple! on, well, literally everything, I started thinking about contributing to the effort.&lt;br&gt;
But were to play Bad Apple on? After some time I got the idea! Playing Bad Apple on a Node process (or multiple processes as I explain later), not by using random &lt;code&gt;console.log&lt;/code&gt;, but rather by throwing errors and letting them display the stack trace on the terminal.&lt;/p&gt;

&lt;p&gt;So there it is:&lt;/p&gt;
&lt;h2&gt;
  
  
  Bad Apple but it's Javascript errors
&lt;/h2&gt;

&lt;p&gt;Bad Apple video played on terminal.&lt;/p&gt;

&lt;p&gt;Note: if you want to follow along with the code, please check &lt;a href="https://github.com/roveroniandrea/bad-apple-js-errors"&gt;my repository&lt;/a&gt; on Github, and if you enjoyed this small project, consider leaving a star (no pressure I &lt;code&gt;Promise&lt;/code&gt; 😄✌️. &lt;del&gt;Ok that joke was terrible&lt;/del&gt;).&lt;br&gt;
You can also check out &lt;a href="https://youtu.be/eLO-nH3dcNk"&gt;this video&lt;/a&gt; I recorded.&lt;/p&gt;
&lt;h2&gt;
  
  
  Let's start
&lt;/h2&gt;

&lt;p&gt;Each frame is a NodeJS process that tries to execute some bugged functions, throwing an Error. The stack trace is printed on the console, resulting in a single frame. By spawning multiple processes on different scripts, the complete Bad Apple video can be rendered.&lt;/p&gt;
&lt;h2&gt;
  
  
  How it works
&lt;/h2&gt;

&lt;p&gt;When an Error is thrown, Node prints its stack trace on stderr, which normally is the console.&lt;br&gt;
For example, this is a stack trace consisting of just one function call:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ node
&amp;gt; function myBuggedFunction() { return null.toString()}
&amp;gt; myBuggedFunction()

Uncaught TypeError: Cannot read properties of null (reading 'toString')
    at myBuggedFunction (REPL10:1:42)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can nest it to create a stack trace with two rows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt; function myBuggedFunction2() { return myBuggedFunction()}
&amp;gt; myBuggedFunction2()

Uncaught TypeError: Cannot read properties of null (reading 'toString')
    at myBuggedFunction (REPL1:1:42)
    at myBuggedFunction2 (REPL2:1:38)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By correctly naming each function, we can print some ASCII art on it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt; function ____$____(){return null.toString()}
&amp;gt; function ___$$$___() {____$____()};
&amp;gt; function __$$$$$__() {___$$$___()};
&amp;gt; function _$$$$$$$_() {__$$$$$__()};
&amp;gt; 
&amp;gt; _$$$$$$$_()
Uncaught TypeError: Cannot read properties of null (reading 'toString')
    at ____$____ (REPL1:1:34)
    at ___$$$___ (REPL2:1:23)
    at __$$$$$__ (REPL3:1:23)
    at _$$$$$$$_ (REPL4:1:23)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The only adjustment needed is to change the maximum stack size that Node has to keep, in order to print all the rows needed:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Allows to keep and print 50 function calls in the stack trace&lt;/span&gt;
&lt;span class="nb"&gt;Error&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;stackTraceLimit&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;50&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;main.js&lt;/code&gt; process loads all bmp files, and for each of them writes the corresponding js file consisting in a function for each image row,&lt;br&gt;
It then spawns a child process via fork for each frame, piping its stderr to the console. It handles all the timings and clears the console between each frame&lt;/p&gt;
&lt;h2&gt;
  
  
  From bmp to error stack trace
&lt;/h2&gt;

&lt;p&gt;Assuming we already have a decoded bmp file (representing a single frame), what we need is to generate some code that, when runned by Node, creates a stack trace that appears like the bmp frame and then throws an error (see example above).&lt;/p&gt;

&lt;p&gt;So we need to name each function like the corresponding row in the bitmap.&lt;br&gt;
For this, there are some constraints regarding which characters can be used as function names. I decided to go with the dollar sign &lt;code&gt;$&lt;/code&gt; for white pixels, and underscores &lt;code&gt;_&lt;/code&gt; for black ones. In order to have unique function names even when generating identical rows, a suffix is added to each function name.&lt;/p&gt;

&lt;p&gt;So each row is converted like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function_name = &amp;lt;row_encoding&amp;gt;__&amp;lt;row_index&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After all js scripts have been generated, the main process spawns multiple subprocesses (one for each script). Since spawning takes some time, childrens are created in advance and put in a queue. Each child then waits for a message from the parent process before calling the bugged functions chain. With the right timing, the parent process sends the start message to each child, resulting in the corresponding error thrown and frame printed onto the console.&lt;/p&gt;

&lt;h2&gt;
  
  
  Resolution VS fps
&lt;/h2&gt;

&lt;p&gt;You can customize both the video resolution and framerate when using ffmpeg.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;To customize the video resolution, change the &lt;code&gt;scale=W:H&lt;/code&gt; property.&lt;/li&gt;
&lt;li&gt;To customize the framerate, you need to adjust both the &lt;code&gt;-r VALUE&lt;/code&gt; property and the target fps when calling the &lt;code&gt;runAll()&lt;/code&gt; function. The first value changes the number of frames generated by ffmpeg, while the second one changes the frequency of which child processes are executed. You need to set both to the same value to keep the video at 1x speed.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Increasing resolution also increases the size of the buffer to print on console for each frame. Writing on the console takes some time, so when settings high resolution and high framerate, it might happen that the next frame starts before the previous one has been fully printed. This causes the console to clear in the middle of a frame print, causing some visual flickering on screen. The best solution would be delaying the next frame until the first one has been completedly printed, thus decreasing the video framerate, hovewer I didn't manage to find a reliable way to tell if the stderr buffer is completely empty and written onto the console, so for now you need manually decrease the fps if you experience flickering.&lt;/p&gt;

&lt;p&gt;With my hardware, I found that a 50x50 resolution works well with 20 fps video, which is &lt;code&gt;1000ms / 20frames/s = 50ms&lt;/code&gt; between each frame. Lower resolutions (30x30 or 20x20) work good at 30 and even 60fps.&lt;/p&gt;

&lt;h2&gt;
  
  
  From .mp4 to .bmp (optimization needed)
&lt;/h2&gt;

&lt;p&gt;Converting from mp4 to bmp is done via &lt;code&gt;ffmpeg&lt;/code&gt;. Since each pixel is only black or white, I tried to generate bitmaps with less bits-per-pixel &lt;code&gt;bpp&lt;/code&gt; as possible, like &lt;code&gt;-pix_fmt monow&lt;/code&gt; that uses a single bit (allowing to represent just black or white for each pixel), or &lt;code&gt;-pix_fmt gray&lt;/code&gt; that uses 8 bits (allowing for 0-255 colors for each pixel). Unfortunately, those bitmaps where generated with some sort of compression or encoding alghorytm which I didn't manage to decode, and I didn't want to use any kind of external library to help me.&lt;/p&gt;

&lt;p&gt;So I switched to &lt;code&gt;-pix_fmt rgb0&lt;/code&gt;, that uses one byte for each color channel (rgb, but not alpha) of a pixel. This pixel format it's not compressed (althought bitmap format spec says it might be) so I managed to make it work, but now I need to reserve 24 bits for storing just a single black or white pixel! This is surely something that can be optimized.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>node</category>
      <category>badapple</category>
    </item>
  </channel>
</rss>
