DEV Community

Abhinav Sachdeva
Abhinav Sachdeva

Posted on

OAuth with Fastify

I was recently trying to setup authentication using OAuth2 for the first time and chose my fastify as my web server. Honestly the amount of information about OAuth on the web is huge and some of it is obsolete, hence this post.

Pre-requisite

  • Register your app at Google Cloud Platform
  • Enable the Google+ API
  • Generate credentials - Client ID, Client secret
  • Setup the authorized origin(front-ends) and redirect(server-routes) URIs like so: Google OAuth

User-interface
Serve a basic HTML page on port 3002. Tip: use Live server for a quick start.

<body>
    <!-- Fastify server runs on localhost:3000 -->
    <a href="http://localhost:3000/api/auth/google>
        Google Login
    </a>
</body>
Enter fullscreen mode Exit fullscreen mode

Setup
Install the fastify plugins required

npm i fastify-cors fastify-oauth2
Enter fullscreen mode Exit fullscreen mode

Create a fastify server

const fastify = require("fastify")({});
Enter fullscreen mode Exit fullscreen mode

Register the CORS plugin

fastify.register(require("fastify-cors"), {
    origin: "*" // allow all origins (BAD)
});
Enter fullscreen mode Exit fullscreen mode

Regster the OAuth2 plugin (using Google OAuth in this example)

const oauthPlugin = require('fastify-oauth2');

fastify.register(oauthPlugin, {
    // Can be any valid variable name you prefer
    // Fastify instance will now have this as a property
    name: 'googleOAuth2', 

    // Gets user's full name, email and profile picture URL
    scope: ['profile email'], 

    credentials: {
        client: {
            id: process.env.GOOGLE_OAUTH_CLIENT_ID,
            secret: process.env.GOOGLE_OAUTH_CLIENT_SECRET
        },

        // plugin-provided configurations for Google OAuth
        auth: oauthPlugin.GOOGLE_CONFIGURATION, 
    },

    // This is automatically registered as a 
    // GET route in your app
    startRedirectPath: '/api/auth/google', 

    // Can be a relative path that serves HTML 
    // or an absolute URL to your front-end app
    callbackUri: 'http://localhost:3000/api/auth/google/callback'
});
Enter fullscreen mode Exit fullscreen mode

Register a route where Google will callback (send the response)

fastify.get("api/auth/google/callback", {}, async  function (req, res) {
    // Fastify instance gets decorated with this method on OAuth plugin initialization
    const token =  await fastify.googleOAuth2.getAccessTokenFromAuthorizationCodeFlow(req);

    console.log({ token }); // Just for debugging

    // Redirect to a route serving HTML or to your front-end
    res.redirect("http://localhost:3002/?token="  + token.access_token)
})
Enter fullscreen mode Exit fullscreen mode

And that's it!
Start the server. Launch the UI in a browser and click the link.

Discussion (1)

Collapse
jenkasia profile image
Evgeniy Kasyan

How i can sign out with fastify-oauth2?