<?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 Jake Engel on Medium]]></title>
        <description><![CDATA[Stories by Jake Engel on Medium]]></description>
        <link>https://medium.com/@jengel3?source=rss-b272f7e21531------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LB6ayH-Vpt9ZGsP30StWmw.png</url>
            <title>Stories by Jake Engel on Medium</title>
            <link>https://medium.com/@jengel3?source=rss-b272f7e21531------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 03:46:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jengel3/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[Service Classes Using Plugins in Nuxt.js]]></title>
            <link>https://medium.com/swlh/service-classes-using-plugins-in-nuxt-js-32c0f387ecb9?source=rss-b272f7e21531------2</link>
            <guid isPermaLink="false">https://medium.com/p/32c0f387ecb9</guid>
            <category><![CDATA[nuxtjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Jake Engel]]></dc:creator>
            <pubDate>Fri, 20 Nov 2020 12:03:21 GMT</pubDate>
            <atom:updated>2020-11-20T18:39:20.702Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6Epo17NbclIPtwno" /><figcaption>Photo by <a href="https://unsplash.com/@maxwbender?utm_source=medium&amp;utm_medium=referral">Max Bender</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Architecting Nuxt applications might seem simple at first — you have your components, pages, and maybe a few plugins. However, as your app grows and the business logic becomes more complex, so does the size and structure of your app. It might not be apparent at first, but as more API calls or other integrations make their way into the codebase you’ll quickly realize how fast these issues can become unmanageable, whether that’s due to repeated code or a poorly designed structure, or lack thereof.</p><p>Let’s take for example API calls. Every application, from a simple todo app to a large-scale eCommerce platform requires HTTP requests to an external API, whether that’s one that you’ve built yourself or by a third party. In some situations, you’ll likely need to call the same API endpoint twice.</p><p>Continuing with the eCommerce platform, consider a feature where you need to display recommendations to a user based on their purchase or viewing history. Rather than only displaying it in one place, you might want to display the recommendations both on the homepage for maximum viewability, but also within their shopping cart to encourage them to purchase more products. These are two completely separate pages, but each needs to load the exact same content from the exact same API endpoint.</p><p>You could simply write out the full API call within each page component, and return the data using Nuxt’s <a href="https://nuxtjs.org/docs/2.x/features/data-fetching#async-data">asyncData</a> function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57b705f1d7966dde7ca95bae5ae2bd81/href">https://medium.com/media/57b705f1d7966dde7ca95bae5ae2bd81/href</a></iframe><p>Sure, that works, but this only covers the recommendations page. What about the homepage? Are you going to copy and paste this code there as well? What happens if the API endpoint to retrieve recommendations changes? Are you going to find every instance of this URL and replace it with the new one?</p><p>Instead, let’s ensure that the code is <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a> (a.k.a. don’t repeat yourself), one of the most important principles in software engineering for writing clean code. Rather than copy and pasting similar lines of code everywhere, we can use a concept called <a href="https://en.wikipedia.org/wiki/Service-oriented_programming">service classes</a>, which will allow us to abstract away common logic, making it clean and reusable.</p><h4>Plugin Injection</h4><p>While neither Vue nor Nuxt are built with a dependency injection architecture in mind like Angular or other frameworks might be, there still remains a simple way to make service classes such as these available everywhere in your app, both for server-side rendering and on the client. In Nuxt, this concept is referred to as <a href="https://nuxtjs.org/docs/2.x/directory-structure/plugins">plugins</a>. These are often used in 3rd party modules, but can be just as useful for structuring your own application logic. Specifically, we’ll want to look further into injecting properties into both the Vue instance and Nuxt app context, <a href="https://nuxtjs.org/docs/2.x/directory-structure/plugins#inject-in-root--context">documented further down the page</a>.</p><p>Injecting properties allows us to make functions or other values available in both the Vue components including lifecycle hooks, templates and methods, as well as in the Nuxt context, which can be accessed in other places such as the asyncData hook within pages, or within additional plugins.</p><p>Let’s take a quick look at the documentation’s injection example as a preview of the functionality that it can provide.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d2b5aa32d109ecdfdd8ed1d8821892a/href">https://medium.com/media/3d2b5aa32d109ecdfdd8ed1d8821892a/href</a></iframe><p>Super simple! The method is injected into every place you could need it — the Vue instance and Nuxt’s context included. Nuxt will also automatically prefix the injected method with a $ to differentiate it from first party methods. The documentation also reminds us that you’ll need to register your plugin within the plugins sections of your nuxt.config.js file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab39890b6dff33cc94c29e3d0d1c1823/href">https://medium.com/media/ab39890b6dff33cc94c29e3d0d1c1823/href</a></iframe><p>With the plugin registered and $hello injected, let’s see how we could use it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0c69bf4f8099e33b7e511237a216a82/href">https://medium.com/media/b0c69bf4f8099e33b7e511237a216a82/href</a></iframe><p>The $hello method is accessible <em>everywhere, </em>providing the exact same functionality without repeating code. Of course, $hello is quite literally a “Hello World!” function and wouldn’t be all that useful, but the possibilities it provides are endless.</p><p>One of the more useful features of the injection functionality, is that injected properties are also available in the VueX store, allowing them to be used within dispatched actions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f1927f4d9168fd256385ff4a1b7b206/href">https://medium.com/media/4f1927f4d9168fd256385ff4a1b7b206/href</a></iframe><p>Again — not very useful without additional logic, but consider the functionality that it <em>could </em>provide, such as fetching and storing data from an API, dispatching UI notifications or handling form validation.</p><h4>Service Classes</h4><p>Forget a single method. Nuxt’s injection supports any type of property, not just functions or static values, but also entire classes.</p><p>Although our $hello method wasn’t all that useful, an entire logging service might be more-so.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b008d297e8b85f494249442bfa75b2e5/href">https://medium.com/media/b008d297e8b85f494249442bfa75b2e5/href</a></iframe><p>Although it’s still simple, it provides an idea of the functionality that service classes could provide.</p><p>Before we can use the class methods, we’ll need to create an instance of the LoggingService and inject it as we did with the previous $hello function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0f8f530f458be9f09c93064f509b5d1/href">https://medium.com/media/c0f8f530f458be9f09c93064f509b5d1/href</a></iframe><p>Simple enough. After you’ve registered your plugin in your nuxt.config.js the LoggingService will be available under the $logging property, just as $hello was, but this time providing multiple functions all encapsulated within a class.</p><p>Let’s put it to work.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/795ee5cbf4bb6b336a0ddc8ff49b42cf/href">https://medium.com/media/795ee5cbf4bb6b336a0ddc8ff49b42cf/href</a></iframe><p>Just as before, the LoggingService methods are accessible throughout the component — within the template, lifecycle hooks, or even the methods. No need to copy and paste console.log(&#39;[My App] .....&#39;) throughout your app anymore.</p><h4>Service Classes &amp; Dependencies</h4><p>Arguably, simple logic such as logging could be imported as individual functions from your typical module, and that’s not necessarily wrong. However, this sort of structure becomes significantly more useful when your classes rely on other dependencies for their functionality.</p><p>Let’s return to the earlier eCommerce example, where the recommendations page needed to display a list of recommended products from an external API. In that example, we made use of the first-party @nuxt/axios module, which simplified our HTTP requests.</p><p>Just as we’ve injected $hello and $logging into the app context, Axios also injected its own $axios property, providing a pre-configured instance of the Axios client for use across components, plugins and VueX. Given that$axios is accessible in the context, we’re just as easily able to inject it into a service class via its constructor, making it accessible to all our class methods.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea63987e3f3e474bdaa3e8683f27ac93/href">https://medium.com/media/ea63987e3f3e474bdaa3e8683f27ac93/href</a></iframe><p>We’ll assume that when RecommendationsService is constructed (before we inject it), it will receive an instance of an Axios client as its only argument. For the sake of the example, we’ll also assume that getRecommendations() returns data in a format similar to the following:</p><pre>/api/recommendations</pre><pre>{<br>  // array of recommendations <br>  data: [<br>    { ... }, <br>  ]<br>}</pre><p>As usual, before we can call our service, we’ll have to inject it, this time by passing the $axios instance from the plugin’s app context.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b828b47a072b23e6767c21195d51e51/href">https://medium.com/media/9b828b47a072b23e6767c21195d51e51/href</a></iframe><p>Having seen the previous modifications to this plugin, and with an understanding of the app context, injecting the RecommendationsService should be fairly straightforward. The $axios instance is simply pulled from the context and passed to the constructor before the class instance is injected.</p><p>Before wrapping up, let’s take a quick look at this service in use, which is definitely more interesting than logging a few messages with our previous service.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1d622a8520e9ed8c268cc16b746e194/href">https://medium.com/media/e1d622a8520e9ed8c268cc16b746e194/href</a></iframe><p>Simply loading a list of recommendations and displaying them to the user, this component offers two methods for accessing the RecommendationsService — either via the asyncData hook, requiring that the data be loaded before the page renders, or via our reloadRecommendations method, which can be called by clicking the button in the template. Although each method accesses the service slightly differently, they both work all the same.</p><p>Want to display you recommendations on another page? No need to rewrite the Axios API call when you can simply refer back to the service class.</p><p>One last thing to point out about our Axios dependency within the RecommendationsService class! You could simply import Axios directly from its module, but keep in mind that doing so would create a new client with the default configuration — not including any modifications (such as a base URL) that the @nuxt/axios plugin has already configured, which are only available via the instance injected into the app context.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b0793e24141d4273cd3e5dc1dcfc147/href">https://medium.com/media/2b0793e24141d4273cd3e5dc1dcfc147/href</a></iframe><p>Just as we injected Axios — any other dependency could be injected including the VueX $store or even the $http HTTP client provided by the @nuxt/http module.</p><h4>Wrapping Up</h4><p>As you continue to build out your Nuxt apps, the need for decoupling logic and creating some sort of service pattern will quickly become apparent.</p><p>There’s various ways to structure such an architecture, but one of the great (but sometimes not so great!) features of Nuxt is that it’s not very opinionated, allowing you to design your app the way that works best for your use cases.</p><p>You might create a new folder for your services, or even wrap all of your API services in a single object, for example, making the recommendations and logging services accessible at app.$api.recommendations and app.$api.logging respectively to prevent polluting the context too much.</p><p>Check out the code samples <a href="https://gist.github.com/jengel3/578c82ba027dde80a4c318a76515fffc">here</a>, and stay tuned for a future article covering improved API service classes, as well as TypeScript integration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32c0f387ecb9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/service-classes-using-plugins-in-nuxt-js-32c0f387ecb9">Service Classes Using Plugins in Nuxt.js</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NestJS — Implementing Access & Refresh Token JWT Authentication]]></title>
            <link>https://javascript.plainenglish.io/nestjs-implementing-access-refresh-token-jwt-authentication-97a39e448007?source=rss-b272f7e21531------2</link>
            <guid isPermaLink="false">https://medium.com/p/97a39e448007</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Jake Engel]]></dc:creator>
            <pubDate>Fri, 13 Nov 2020 11:02:27 GMT</pubDate>
            <atom:updated>2020-11-16T16:35:46.087Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X5dlhMe6jk957iV7" /><figcaption>Photo by <a href="https://unsplash.com/@lanceanderson?utm_source=medium&amp;utm_medium=referral">Lance Anderson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>NestJS — Access &amp; Refresh Token JWT Authentication</h3><p>If you’re building apps in Node.js then you might be familiar with <a href="https://nestjs.com/">NestJS</a>, a self-described feature-packed framework for building server-side applications. Think of it as the Laravel, Ruby on Rails or Flask for Node. NestJS allows us to rapidly build out services with the basics such as routing, validation and database access already packaged in.</p><p>Thankfully, authentication is also given first-party support, with support for various providers via passport and multiple guards, including JWT — today’s topic. Nest provides a basic <a href="https://docs.nestjs.com/techniques/authentication#jwt-functionality">guide</a> to JWT implementation, but it doesn’t necessarily include all the features that your typical app might require.</p><p>Let’s take a look at a custom and feature-complete implementation that you can roll in your own application. For simplicity’s sake, we’ll assume that you have an existing project based on Nest’s setup guide and a basic understanding of the various components that Nest provides.</p><h4>Getting Started</h4><p>Let’s start by installing Nest’s first-party authentication packages, which will provide 90% of the logic for our implementation, as well as a few external modules for additional support.</p><pre>$ npm install --save @nestjs/passport @nestjs/jwt passport passport-local passport-jwt bcrypt class-validator</pre><pre>$ npm install --save-dev @types/passport-local @types/passport-jwt @types/bcrypt @types/jsonwebtoken</pre><p>Cool! <a href="https://www.npmjs.com/package/@nestjs/passport">@nestjs/passport</a> and <a href="https://www.npmjs.com/package/@nestjs/jwt">@nestjs/jwt</a> are Nest’s first-party packages, offering the basic functionality, while <a href="https://www.npmjs.com/package/passport">passport</a>, <a href="https://www.npmjs.com/package/passport-local">passport-local</a> and <a href="https://www.npmjs.com/package/passport-jwt">passport-jwt</a> are the “standard” packages authentication in Node. We’ll also include <a href="https://www.npmjs.com/package/bcrypt">bcrypt</a> for hashing support and <a href="https://github.com/typestack/class-validator">class-validator</a> for request validation. We’ll also of course include the types for these packages (assuming you’re using TypeScript, which you should be!), as well as the types for <a href="https://www.npmjs.com/package/jsonwebtoken">jsonwebtoken</a>, which is already included as a dependency of @nestjs/jwt.</p><p>With the dependencies installed, let’s discuss the basic structure of our app. While implementing the authentication, we’ll tie together two modules which we’ll refer to as the UsersModule and the AuthenticationModule using Nest’s <a href="https://docs.nestjs.com/modules">modules</a> system. While we won’t focus specifically on the database portion of this implementation, we will discuss a general structure that works well and stores the most essential data. The user data will be handled by our UsersService and UsersRepository , leaving the refresh tokens to be handled by the RefreshTokensRepository and all tied together by the TokensService logic.</p><p>While the database implementation is less important and will work with whatever provider you choose — Sequelize, TypeORM, MongoDB, etc. we’ll still need to create two models/entities to support our authentication and user modules. Once again, for the sake of simplicity, we’ll use Nest’s <a href="https://docs.nestjs.com/techniques/database#sequelize-integration">first-party Sequelize package</a>, but converting it to the package of your choosing should be fairly straightforward.</p><p>Let’s put it all together in tree form for an idea of what you’ll end up with.</p><pre>app/<br>|-- application.module.ts<br>|-- requests.ts<br>|-- modules/<br>    |-- users/<br>        |-- users.module.ts<br>         -- users.service.ts<br>    |-- authentication<br>        |-- authentication.module.ts<br>         -- authentication.controller.ts<br>         -- refresh-tokens.repository.ts<br>         -- tokens.service.ts<br>         -- jwt.guard.ts<br>         -- jwt.strategy.ts<br>|-- models/<br>    |-- user.model.ts<br>    |-- refresh-token.model.ts</pre><p>There’s a few files that we haven’t discussed such as requests.ts and jwt.guard.ts but their usage will be more apparent later on.</p><p>Of course everything can be tailored to fit your app’s structure, and you may even choose to create a separate module for tokens or create an additional folder or folders to further separate your repositories and services.</p><h4>Users and Tokens</h4><p>Now that we’ve laid out the structure of our app, we can get down to the important part — the logic. First, we should probably talk users, since they’re at the core of authentication.</p><p>We’ll use the simplest form of a User model, one which contains two properties — a username and password but can easily be modified to add any additional information that you may desire.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/266c048aaa5669f5aeb1c2459f335006/href">https://medium.com/media/266c048aaa5669f5aeb1c2459f335006/href</a></iframe><p>The model definition is fairly straightforward, but you can read more about Sequelize’s TypeScript implementation <a href="https://github.com/RobinBuschmann/sequelize-typescript#readme">here</a>.</p><p>While we’re here, we’ll also create a RefreshToken model, which will allow us to store reusable refresh tokens for each user, while also supporting set expiration dates and revocability.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a03e99e9359bac0245a3dd5505af737b/href">https://medium.com/media/a03e99e9359bac0245a3dd5505af737b/href</a></iframe><p>The user_id column of course refers to the owning-user, is_revoked offering the ability to immediately revoke a token, and expires providing a timestamp for automatic revocation. <em>Technically, </em>we don’t necessarily need to include an expires field because we’ll embed the expiration date in the refresh token, but storing it in the database allows us to optionally purge expired tokens in the future.</p><p>Models are done, but we’ll need a way to store and retrieve their data. Let’s create a couple repository classes that provide reusable functionality for this.</p><p>If we think ahead, we’ll need a few methods — one to find a user by their ID for generating refresh tokens, one to find them by their username at login, and a final method to create a new user for registration.</p><p>As mentioned earlier, we’ll refer to this class as the UsersRepository with an implementation similar to the following.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b19d09eee42943ce87034dcfc545df94/href">https://medium.com/media/b19d09eee42943ce87034dcfc545df94/href</a></iframe><p>If this is your first look at a class making use of Sequelize models in NestJS, make sure to check out their reference guide <a href="https://docs.nestjs.com/techniques/database#models">here</a>, especially in reference to the constructor injections.</p><p>Both findForId(id) and create(username, password) are self-explanatory, while findByUsername(username) might be slightly more complex because of the interpolated Sequelize functions for adding support for case-insensitive username logins. Thankfully, each of these built-in functions are described in the <a href="https://sequelize.org/master/manual/model-querying-basics.html">Sequelize documentation</a> for quick reference.</p><p>Before we tie everything together in the services and controllers, let’s add one last repository for our refresh tokens. We’ll need the ability to create a token, as well as find one by its ID.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67c9326dd0345224efcd7a29d163fa4c/href">https://medium.com/media/67c9326dd0345224efcd7a29d163fa4c/href</a></iframe><p>Again, fairly straightforward. We’ll create a new RefreshToken by associating it with a User and setting the expiration date based on the ttl parameter, specifying the number of seconds until the token expires.</p><p>As a side note — in the first repository, we used Sequelize’s <a href="https://www.npmjs.com/package/sequelize-typescript#repository-mode-1">repository pattern</a>, but used the static access methods for the refresh tokens. The latter allows for directly accessing methods like find and findOne from the model class, while the repository pattern allows for a better separation of concerns — but either method is equally correct.</p><h4>Service Layer</h4><p>The database logic is done. We’ve created methods for creating and retrieving new users and their refresh tokens, but we’ll need a one last layer between our repositories and API controllers — our services, which will provide the business logic connecting the two.</p><p>First up, we’ll want to create reusable logic for generating access and refresh tokens, which is where our TokensService will come into play.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df2e01edb167ebdf6f20ff4340443d12/href">https://medium.com/media/df2e01edb167ebdf6f20ff4340443d12/href</a></iframe><p>Let’s take a more in-depth look at what we’re implementing.</p><p>First of all, we’ll setup our class by injecting the RefreshTokensRepository class that we created earlier. We’ll also inject Nest’s built-in <a href="https://github.com/nestjs/jwt/blob/master/lib/jwt.service.ts">JwtService</a> class, which provides wrapping functions around <a href="https://www.npmjs.com/package/jsonwebtoken">jsonwebtoken</a> for signing and decoding JWTs. We’ll also setup a constant variable that declares the claims that will be shared across all tokens we generate — refresh and access alike. Although they’re not strictly necessary, they can provide additional validation for your token. All potential claims are documented in the <a href="https://tools.ietf.org/html/rfc7519#section-4.1.1">JWT RFC</a>.</p><p>Onto the methods. Our first method, generateAccessToken is the simpler of the two. Given a User we can ask our injected JwtService to sign an access token with our BASE_OPTIONS claims, as well as an additional subject claim (sub for short), which will identify the user for which the token was generated. This will be embedded in the JWT, allowing us to later decode it and quickly retrieve the user from the database based on their ID.</p><p>You might wonder if this is secure. Thankfully, the JWT payload is by design immutable. Since the payload is verified by a hash of its contents, a payload modified by a potential hacker or wrongdoer would be considered invalid by the server, which we’ll see in a moment.</p><p>We’ll return the signed JWT as a string, which we later return to the client in the API controller.</p><p>As for the remaining method — generateRefreshToken — we’ll use very similar logic for signing our refresh tokens. Given that the method accepts an expiresIn parameter, we will once again pass this onto the signing options, allowing us to specify the expiration date of the refresh token. In addition, we need to include the jwtid claim (jit for short), which functions as its name suggests, embedding the ID of the token. In the exact same way that we’ll be able to look up the User by the subject claim, we can just as easily pull the RefreshToken by the ID decoded from the claim later on.</p><p>Assuming that those methods are in place, we can extend the class a little further. With the logic for initially generating access and refresh tokens ready, we’re just missing a couple methods for generating access tokens from the refresh tokens.</p><p>Let’s add some additional methods to the TokensService class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09d55072fa84f28e089e0e5b988393ae/href">https://medium.com/media/09d55072fa84f28e089e0e5b988393ae/href</a></iframe><p>Five new methods, but they each implement small pieces of the larger puzzle, making them easy to decipher.</p><p>Let’s take a look at decodeRefreshToken first, which is passed a string—a.k.a the encoded JWT. Once again, we’ll use the built in JwtService but this time using verifyAsync which will decode the JWT token and return its payload in object form.</p><p>Speaking of — we should define what we expect that payload to look like. We’ll use a TypeScript interface, naming it RefreshTokenPayload with two properties: jti and sub which are the proper versions of the full claim that we passed into signAsync earlier, jwtid and subject respectively. These two properties will return the <em>exact </em>same values that were embedded when the token was signed.</p><p>You might also note that we intentionally capture the built in TokenExpiredError from jsonwebtoken when decoding the token. As we mentioned earlier, we don’t necessarily need to store the expiration date in the database because this logic will ensure the expiration date embedded in the JWT is valid. We’ll also catch any additional errors and return them in a format that the controllers will understand.</p><p>Two other methods getUserFromRefreshTokenPayload and getStoredTokenFromRefreshTokenPayload are fairly self-explanatory, and do almost exactly what you might assume from their names. Given a decodedRefreshTokenPayload that we defined earlier, the methods will simply extract the necessary field from the payload and find and return either the User or RefreshToken respectively. As with before, we’ll throw exceptions here in case the fields are not present in the decoded payload.</p><p>With the ability to decode refresh tokens and retrieve their associated token and user records from the database, we can bring this functionality together to create our resolveRefreshToken method, which will decode and return both the RefreshToken and User models from the database, assuming that the token is valid and passes all additional checks that we’ve put in place.</p><p>Given the refresh token as a string, we will decode the payload and fetch the RefreshToken from the database. Assuming that the token exists, and that its is_revoked field hasn’t been toggled, we’ll be able to retrieve the user from the database before returning both the user and token.</p><p>In our final method, createAccessTokenFromRefreshToken we can simply use the resolveRefreshToken method that we just implemented to retrieve the User from a refresh token, based on the sub, and then generate a new access token for that user.</p><p>Tokens? Done. Users? Almost.</p><p>While we’re here, let’s create a super simple UsersService to provide additional functionality to the earlier UsersRepository that we created.</p><p>Personally, I like to use the service classes to handle the business logic, and repositories to interact with the database, but it’s totally dependent on your own preferences. In this case, I’ll use the service layer to handle the interaction between the request itself and the database. Before we can create this service, and more importantly before we can create our controllers, we’ll need to define our HTTP request bodies, for which we’ll make use of <a href="https://github.com/typestack/class-validator">class-validator</a>, which as with many other features, Nest provides <a href="https://docs.nestjs.com/techniques/validation#auto-validation">first-class support</a>.</p><p>We’ll setup our requests in our requests.ts file, but you can choose to split these into several files in any structure that you’d like.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b4ad445e01239ac7d17dce954a363a5/href">https://medium.com/media/2b4ad445e01239ac7d17dce954a363a5/href</a></iframe><p>All three request classes are fairly self-explanatory, one providing login functionality, another registration, and the final requiring a refresh_token which will allow us to generate a new access token.</p><p>The requests are defined, so let’s create our UsersService class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/788950fccca739103063bb13351686b9/href">https://medium.com/media/788950fccca739103063bb13351686b9/href</a></iframe><p>Each method is essentially a wrapper around existing logic, but makes implementing it less verbose and easily reusable. The validateCredentials method uses bcrypt’s <a href="https://www.npmjs.com/package/bcrypt#to-check-a-password">compare</a> function to compare the user’s hashed password stored in the database to the password that they attempted to use to login. The last <em>new</em> method, createUserFromRequest takes in a RegisterRequest object from the requests defined earlier, validates the uniqueness of the username and then passes it and the password onto the UsersRepository to create a new user. The final two methods simply proxy the call into our UsersRepository which prevents us from having to inject both the repository <em>and</em> service later on.</p><h4>API Controller Routes</h4><p>The business logic is <strong>done.</strong> That was exhausting. It’s time to bring every component together to create the most essential piece — the routing. In this instance, we’ll only use one controller — our AuthenticationController providing methods to register, login and refresh our users and their tokens.</p><p>We’ll probably want to start with our register endpoint, since there’s no point in trying to login or refresh users that don’t even exist!</p><p>Let’s setup our AuthenticationController by injecting our UsersService and TokensService from earlier, as well as implementing our register method. We’ll also want to add Nest’s @Controller() decorator, setting up the controller’s base path at /api/auth making our registration endpoint available at /api/auth/register as a POST request.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4534480fb9c73fbccb0e542fabffd4d0/href">https://medium.com/media/4534480fb9c73fbccb0e542fabffd4d0/href</a></iframe><p>As with the rest of the logic, we’re keeping things simple. We’re creating a user by passing the request body as a RegisterRequest containing our username and password attributes into our UsersService which will handle creating our new user. We’ll then take the newly created user and generate an access token, as well as a refresh token expiring in 30 days.</p><p>We’ve also added a private helper method to the controller called buildResponsePayload accepting the user, access token, and optionally a refresh token as parameters. We’ll re-use this function multiple times to build a formatted payload to return as a response from each of our authentication endpoints. In doing so, we also defined our AuthenticationPayload interface, representing the exact structure that we expect to receive each time this method is called.</p><p>Now that we can register users, let’s add a method to log them in, available at/api/auth/login also via POST request. The logic is nearly identical to the registration endpoint, but instead of creating the user, it will be resolved from the username and password.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc2af010661b1d2ff493c4d08ece20d4/href">https://medium.com/media/bc2af010661b1d2ff493c4d08ece20d4/href</a></iframe><p>We’ll only need to review the first few lines of the login method. Since we’ll need to verify the password after retrieving the user, we’ll first attempt to find the User record by their username, using the UsersService method created earlier.</p><p>Assuming the user exists, we’ll attempt to match the inputted password against the hashed password in the database, once again using the validateCredentials method from our UsersService class.</p><p>If the user doesn’t exist or the password doesn’t match, we’ll throw an UnauthorizedException to inform the user of an invalid username or password. Otherwise, we’ll continue on to the <em>exact same</em> logic that we used to generate access and refresh tokens for a newly registered user.</p><p>Almost done! Let’s create our last endpoint to refresh users — /api/auth/refresh also available as a POST request. This endpoint will accept a refresh_token in the body, which we will use to identify the user and generate the new access token.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2331ba62429ccf130e588dfb7818b34/href">https://medium.com/media/b2331ba62429ccf130e588dfb7818b34/href</a></iframe><p>Thanks to our TokensService the logic within this method is extremely simple. We’ll need to extract the refresh_token from the request body, and pass it into our createAccessTokenFromRefreshToken method, which will return both the User, as well as the new and encoded access token in string form. Once again, we can build the response payload, but this time without the additional refreshToken parameter. You could also choose to generate a new refresh token every time, but for the purposes of this article we’ll stick to reusing refresh tokens for the time being.</p><h4>Module Registration</h4><p>Controllers are done! At this point we could just about test it out, but we’ll need to register all our services, repositories and controllers in our modules first.</p><p>Since we chose to use two modules, our AuthenticationModule and UsersModule we’ll simply need to configure and register both of these before starting our application.</p><p>Let’s setup our UsersModule first, since the former will depend on it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9081fa6d68691d1c8f1eff69536ee8ae/href">https://medium.com/media/9081fa6d68691d1c8f1eff69536ee8ae/href</a></iframe><p>If you’ve ever registered a <a href="https://docs.nestjs.com/modules">module</a> in NestJS before, this syntax should be familiar. Both the UsersService and UsersRepository are setup as providers and then exported for use in other modules. The User model has also been imported via Sequelize so that it can be resolved by those classes.</p><p>With its dependency registered, we can also setup our AuthenticationModule.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2deeb3fd61996cec3ec05e9d2f4d2f53/href">https://medium.com/media/2deeb3fd61996cec3ec05e9d2f4d2f53/href</a></iframe><p>Similar to before, we’ll setup our TokensService and RefreshTokensRepository as providers, as well as registering our AuthenticationController from earlier. RefreshToken will also be imported just as the User model was, as well as the UsersModule dependency that was registered prior to this one.</p><p>Since our TokensService depends on Nest’s built-in JwtService the JwtModule also needs to be registered for use within the module. We can review the options from the documentation, but we’ll specifically need to specify a secret as well as the signOptions.expiresIn which refers to the lifetime of the <em>access</em> token (not the refresh token!). This parameter accepts either an integer specifying the lifetime in seconds, or a timespan such as 5m or 60s representing five minutes or sixty seconds respectively. The secret should of course be kept private, and never exposed in a GitHub repository or to the end-user. Plan to use Nest’s suggested <a href="https://docs.nestjs.com/techniques/configuration">configuration setup</a>, or your own implementation to store the key privately.</p><p>Finally, you’ll want to register both of these modules as well as the models in your ApplicationModule before testing.</p><p>They can simply be added to the imports array, within the class.</p><pre>// application.module.ts<br>...</pre><pre>imports: [<br>  UsersModule,<br>  AuthenticationModule,<br>],</pre><pre>...</pre><p>Please see the <a href="https://docs.nestjs.com/techniques/database#sequelize-integration">Nest documentation</a> for registering the Sequelize module, including the host, password, etc. as well as your model classes.</p><p>Modules? Registered.</p><h4>Ready To Go</h4><p>Assuming the app was correctly setup with a main.ts file as suggested in the Nest documentation, it should successfully start and register all the classes that we’ve created.</p><pre>$ nest start --watch</pre><p>Let’s test out our registration endpoint. We’ll also assume that our server is running on localhost port 3000.</p><pre>curl http://127.0.0.1:3000/api/auth/register \<br>  -H &quot;Content-Type: application/json&quot; \<br>  --data &#39;{&quot;username&quot;: &quot;jsmith&quot;, &quot;password&quot;: &quot;test123&quot;}&#39;</pre><p>Assuming it worked, we should see a response containing the user data, an access token and its respective refresh token.</p><pre>{<br>   &quot;status&quot;: &quot;success&quot;,<br>   &quot;data&quot;: {<br>      &quot;user&quot;: {<br>         &quot;username&quot;: &quot;jsmith&quot;<br>      },<br>      &quot;payload&quot;: {<br>         &quot;type&quot;: &quot;bearer&quot;,<br>         &quot;token&quot;: &quot;eyJ......HNA&quot;,<br>         &quot;refresh_token&quot;: &quot;eyJ......UEk&quot;<br>      }<br>   }<br>}</pre><p>Looks good! Let’s test out the login endpoint.</p><pre>curl http://127.0.0.1:3000/api/auth/login \<br>  -H &quot;Content-Type: application/json&quot; \<br>  --data &#39;{&quot;username&quot;: &quot;jsmith&quot;, &quot;password&quot;: &quot;test123&quot;}&#39;</pre><p>It’s the exact same response, but with of course a different access and refresh token. Before we finish up, let’s give the refresh endpoint a shot.</p><pre>curl http://127.0.0.1:3000/api/auth/refresh \<br>  -H &quot;Content-Type: application/json&quot; \<br>  --data &#39;{&quot;refresh_token&quot;: &quot;eyJ......UEk&quot;}&#39;</pre><p>The response to this is similar, but lacks a new refresh token since we chose <em>not</em> to generate new refresh tokens. You can of course choose to generate a new refresh token every time.</p><pre>{<br>   &quot;status&quot;: &quot;success&quot;,<br>   &quot;data&quot;: {<br>      &quot;user&quot;: {<br>         &quot;username&quot;: &quot;jsmith&quot;<br>      },<br>      &quot;payload&quot;: {<br>         &quot;type&quot;: &quot;bearer&quot;,<br>         &quot;token&quot;: &quot;eyJ......HNA&quot;,<br>      }<br>   }<br>}</pre><h4>Authenticated Routes</h4><p>Now what? We’ve generated access tokens and refresh tokens, and even used the refresh tokens to generate access tokens.</p><p>We could wrap up here, but what about making authenticated requests?</p><p>The entire point of implementing authentication is to identify users or for accessing protected resources — such as a user’s profile, order history, or whatever other feature that can’t be exposed to the public.</p><p>Rather than having to re-implement the access token check for every method, let’s extend @nestjs/jwt’s built JwtGuard and JwtStrategy implementations.</p><p>We’ll create JwtStrategy as jwt.strategy.ts within the authentication module.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f06b7db6d37bd78b7704b3e9201d788/href">https://medium.com/media/4f06b7db6d37bd78b7704b3e9201d788/href</a></iframe><p>In the class constructor, we’re specifying similar options as when we first configured the JwtModule earlier on. The same secret should be specified, as well as the same token lifetime. We’ve also added the jwtFromRequest option to specify where the access token is accessible, in this case using the Authorization header, via the ExtractJwt.fromAuthHeaderAsBearerToken built into passport-jwt documented <a href="http://www.passportjs.org/packages/passport-jwt/">here</a> along with the other possible extraction options.</p><p>We’ve also defined our AccessTokenPayload which provides the same functionality as the RefreshTokenPayload that was defined earlier for accessing the decoded payload of the refresh token. The access token’s payload will be passed into the validate function, which is a wrapper around passport-jwt to retrieve the User record.</p><p>We’ll extract the sub attribute from the payload, once again short for subject which identifies the user ID for which the access token represents. Assuming that the ID is valid, we can fetch the user from our UsersService and return it. The user will now be accessible in the HTTP request via the @Req() decorator within the controllers.</p><p>Before adding an authenticated route, we also need to add a JwtGuard which will provide the actual authentication protection for the routes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a4ba2b7e981e5320dd091438697f71f/href">https://medium.com/media/1a4ba2b7e981e5320dd091438697f71f/href</a></iframe><p>This is simply an extension of <a href="https://docs.nestjs.com/techniques/authentication#extending-guards">Nest’s authentication guards</a>, throwing an error if err or info are passed to handleRequest or potentially throwing its own UnauthorizedException if the user is null for whatever reason.</p><p><strong>Important:</strong> The JwtGuard needs to be added to the list of providers within your AuthenticationModule for it to be registered and usable.</p><p>Our guard is registered and ready to authenticate users. Let’s added an authenticated route in our AuthenticationController to return the logged in user’s profile.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/639ce1fa5fd8cf3bc80593e04493a7ae/href">https://medium.com/media/639ce1fa5fd8cf3bc80593e04493a7ae/href</a></iframe><p>Using the @Req() decorator, we’ll be able to access the request, which is now injected with the logged in User thanks to the additional @UseGuards(JWTGuard) attached to the method. Our guard will automatically validate and authenticate the user using the access token and then make it accessible in the request. We can then user the user’s ID to find their database record and return it to the client.</p><p>Let’s try that out.</p><pre>curl http://127.0.0.1:3000/api/auth/me \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -H &quot;Authorization: Bearer eyJ......UEk&quot;</pre><p>Success! The response is pretty similar to our authentication payloads, but only returns the user’s information without any additional tokens.</p><pre>{<br>   &quot;status&quot;: &quot;success&quot;,<br>   &quot;data&quot;: {<br>      &quot;username&quot;: &quot;jsmith&quot;<br>   }<br>}</pre><p>Now you can protect any resource with minimal effort.</p><h4>Wrapping Up</h4><p>Authentication isn’t an easy topic — and this article is fairly long-winded for that reason, but covers the most problematic parts of implementing such a system in Nest and tries to simplifies it as best as possible.</p><p>There’s bound to be things I’ve missed, or points that could be further clarified on, or even logic that could have been implemented in an entirely different (or better!) way but Nest, Passport, Sequelize and all the other packages used here provide easily accessible and useful documentation that can be extremely helpful. In case all the code samples aren’t clear as small snippets, they can be viewed together <a href="https://gist.github.com/jengel3/6a49a25b2fc2eb56fcf8b38f5004ea2c">here</a> or in the <a href="https://github.com/jengel3/nestjs-auth-example">sample repository</a>.</p><p>If you’re looking to use this implementation in Vue, I’ve written an entire article on doing so <a href="https://medium.com/swlh/jwt-authentication-in-vue-nuxt-the-right-way-486e333b1d71">here</a>, with this exact setup in mind.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97a39e448007" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/nestjs-implementing-access-refresh-token-jwt-authentication-97a39e448007">NestJS — Implementing Access &amp; Refresh Token JWT Authentication</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JWT Authentication in Vue/Nuxt — The Right Way]]></title>
            <link>https://medium.com/swlh/jwt-authentication-in-vue-nuxt-the-right-way-486e333b1d71?source=rss-b272f7e21531------2</link>
            <guid isPermaLink="false">https://medium.com/p/486e333b1d71</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[single-page-applications]]></category>
            <category><![CDATA[nuxtjs]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Jake Engel]]></dc:creator>
            <pubDate>Fri, 30 Oct 2020 17:14:26 GMT</pubDate>
            <atom:updated>2020-11-05T20:56:07.153Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4y_zCofrm6zQyrKJ" /><figcaption>Photo by <a href="https://unsplash.com/@sawyerbengtson?utm_source=medium&amp;utm_medium=referral">Sawyer Bengtson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>JWT Authentication in Vue/Nuxt — The Right Way</h3><p>Authentication in SPAs is often a hot topic, and even more-so for those who aren’t sure of the best method for implementing an authentication system with all the necessary features and one that can handle the most common edge cases.</p><p>Although we won’t cover writing the backend <a href="https://jwt.io/">JWT</a> or authentication implementation, there are various articles that describe the best methods for various languages and frameworks, depending on your needs. Regardless of your choice, you’ll want to make sure to implement the three core features necessary for the frontend — registration, login and access token refreshing via <a href="https://auth0.com/blog/refresh-tokens-what-are-they-and-when-to-use-them/">refresh tokens</a>. We’ll discuss a basic implementation of some of these endpoints, but they are still completely flexible. It’s also assumed that you have already setup a basic Nuxt application in universal rendering mode.</p><h4>Getting Started</h4><p>For the frontend, we’ll be making use of three essential packages — <a href="https://www.npmjs.com/package/vuex-persistedstate">vuex-persistedstate</a>, <a href="https://www.npmjs.com/package/js-cookie">js-cookie</a> and <a href="https://www.npmjs.com/package/@nuxtjs/axios">@nuxtjs/axios</a>. The first allows us to persist Nuxt module state into a store of our choosing (cookies!), which will allow us to store tokens and user data accessible to both the Nuxt server, as well as the client, which in turn allows for authenticated calls from both ends. The second will make parsing cookies easier, while the last is a common Nuxt package, providing an all-inclusive package for HTTP calls.</p><p>Let’s start by installing those.</p><pre>npm install --save vuex-persistedstate js-cookie @nuxtjs/axios</pre><h4>VueX State Persistence</h4><p>To make authenticated API calls from both the server and browser (client), we need to ensure that the tokens are accessible from both ends. vuex-persistedstate simplifies this, and with the help of js-cookie will persist the tokens to a cookie.</p><p>After installing the packages, we’ll need to configure the vuex-persistedstate with a plugin.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cebc7a3618843fe84b1807248db8fdd/href">https://medium.com/media/4cebc7a3618843fe84b1807248db8fdd/href</a></iframe><p>Don’t forget to add this plugin to your nuxt.config.js!</p><pre>plugins: [<br>  &#39;~/plugins/local-storage&#39;,<br>],</pre><h4>VueX Store</h4><p>We’ll also need to setup the VueX store, which will be where we store data about the user, the access token and refresh token. We’ll also need to include actions for making API calls to register, login and refresh a user, as well as mutations to commit the returned data to the state.</p><p>Although the structure is easily modifiable, you should end up with something like this…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70fbced81dbb195b19234aa23affc382/href">https://medium.com/media/70fbced81dbb195b19234aa23affc382/href</a></iframe><p>Now that we have a state in place, you’ll need to create form components for the login and registration pages, which also won’t be covered here. Essentially, your forms should call the authentication module actions to login or register the user.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6af75e549cb8c9fd466fd6195039e216/href">https://medium.com/media/6af75e549cb8c9fd466fd6195039e216/href</a></iframe><p>With the state and forms in place, and the ability to authenticate users, we can implement authenticated API requests!</p><h4>Authenticated API Requests</h4><p>For this portion, we’ll make use of Axios’ built-in <a href="https://github.com/axios/axios#interceptors">interceptors feature</a>, which allows us to modify requests and responses, as well as capture all errors. Thankfully, @nuxtjs/axios provides <a href="https://axios.nuxtjs.org/extend#adding-interceptors">first-class support</a> for this feature.</p><p>We’ll use a request interceptor to attach the access token to every API request.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1aa3357b1512bc2a985bc8f012e1193/href">https://medium.com/media/e1aa3357b1512bc2a985bc8f012e1193/href</a></iframe><p>This plugin is fairly straightforward — capturing every request and if the user is authenticated, adding a new Authorization header to the request.</p><p>Don’t forget to add this plugin to your nuxt.config.js, just as before.</p><pre>plugins: [<br>  &#39;~/plugins/local-storage&#39;,<br>  &#39;~/plugins/axios&#39;,<br>],</pre><h4>Refresh Tokens</h4><p>However, what happens when the access token expires? For security reasons, access tokens shouldn’t be long-lived and should be easily revocable if necessary.</p><blockquote>When access tokens expire or become invalid but the application still needs to access a protected resource, the application faces the problem of getting a new access token without forcing the user to once again grant permission. To solve this problem, OAuth 2.0 introduced an artifact called a <a href="https://auth0.com/docs/tokens/refresh-token/current">refresh token</a>. A refresh token allows an application to obtain a new access token without prompting the user.<br> — <a href="https://auth0.com/learn/refresh-tokens/">“Understanding Refresh Tokens”</a> via <a href="https://auth0.com/">auth0</a></blockquote><p>To handle this, we can modify our existing interceptor plugin, adding an error handler to automatically attempt to refresh the access token in the event that it expires. Before we do so, let’s discuss how API should handle expired refresh tokens and the refresh API endpoint itself.</p><p>In the event of an expired access token, the API needs to inform the client that the token is no longer valid and needs to be refreshed. This is most often done by returning a 401 status code and some sort of descriptive payload.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d082568f696744f68b41b5da157e8b41/href">https://medium.com/media/d082568f696744f68b41b5da157e8b41/href</a></iframe><p>The structure of the payload is completely flexible — but for simplicity’s sake, we’ll use this format for demonstration purposes.</p><p>Now that the client is aware of the expired token, it can move onto attempting to refresh the token, before eventually retrying the initial request.</p><p>As for the refresh endpoint — given a refresh_token value via a <strong>POST </strong>request, the API should generate a new access token, and <em>optionally </em>a new refresh token that should be returned to the client. If the refresh token is expired, revoked or otherwise invalid, it can also return an error to let the client know that user cannot be re-authenticated and should be logged out.</p><p>With that in mind, let’s modify the existing interceptor plugin to add the error handler.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26c1beb6369d6c022c26325a6d371242/href">https://medium.com/media/26c1beb6369d6c022c26325a6d371242/href</a></iframe><p>The plugin is documented for more specifics, but essentially the new interceptor checks if the error is related to an expired token, and then attempts to refresh the access token if present.</p><p>If the refresh succeeds, the Promise will <em>return a copy of the original request</em>, making the calling function completely unaware that the token was refreshed before receiving its expected response.</p><p>However, if the refresh fails for whatever reason (i.e. revoked, expired, or invalid refresh token), the interceptor will automatically logout the user and redirect them home.</p><p>With the final modification to the interceptor plugin in place, we can now make authenticated requests that will automatically refresh the access token if necessary!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94401550ffe6f16d47e43efd2226d4a0/href">https://medium.com/media/94401550ffe6f16d47e43efd2226d4a0/href</a></iframe><p>If the access token is valid, we’ll get our expected response! If it’s expired or otherwise invalid, our plugin will attempt to refresh the token, and (assuming it’s successful) still return our expected response!</p><p>Before we wrap up, let’s make one last addition to our VueX store.</p><p>Nuxt provides the <a href="https://nuxtjs.org/guide/vuex-store/#the-nuxtserverinit-action"><strong>nuxtServerInit</strong></a><strong> </strong>hook for the initial SSR request to the server. Using this, we can automatically refresh the access token when a logged-in user first connects to the server. Since we’re using SPA technology, the page is not often refreshed, so when it is we can assume that a short-lived access token is likely expired. This action needs to be added to your root store module.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b1d7f64855b895e5cb651e20c32b675/href">https://medium.com/media/1b1d7f64855b895e5cb651e20c32b675/href</a></iframe><p>Now, when the user navigates to your application via the URL bar or an external inbound link, we’ll automatically refresh their token if they were previously logged in.</p><h4>Epilogue</h4><p>Of course this tutorial doesn’t cover every edge case and isn’t 100% feature complete, but provides the essential implementation for universal client and server-side JWT authentication in a Nuxt application. Authentication is a critical part of every app, and should be thoroughly tested for security issues before releasing publicly.</p><p>Checkout all the code samples <a href="https://gist.github.com/jengel3/5cc40d23b2620683c1f2862de7f72b9a">here</a> or read more about refresh tokens <a href="https://auth0.com/learn/refresh-tokens/">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=486e333b1d71" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/jwt-authentication-in-vue-nuxt-the-right-way-486e333b1d71">JWT Authentication in Vue/Nuxt — The Right Way</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>