0.1.4 • Published 2 years ago

@lightspeed/next-auth v0.1.4

Weekly downloads
5
License
MIT
Repository
-
Last release
2 years ago

@lightspeed/next-auth

npm version

Introduction

Libraries for easily integrating an OAuth2 flow with your Next.js application.

Quick Start

  1. Install the required dependencies in your webapp.
yarn add @lightspeed/next-auth express-session body-parser uid-safe
  1. In your custom server implementation, ensure you have request body parsing and session management implemented. Your configuration may vary.
const uid = require('uid-safe');
const bodyParser = require('body-parser');
const session = require('express-session');

server.use(bodyParser.urlencoded({ extended: false }));
server.use(
  session({
    secret: uid.sync(18),
    resave: false,
    saveUninitialized: false,
  }),
);
  1. In your custom server, instantiate your auth middleware via configuration.
import { useOAuth2 } from '@lightspeed/next-auth';

const { login, logout, callback, refresh, graphql, protectRoute } = useOAuth2(server, {
  authorizationURL: `${process.env.AUTH_SERVICE_BASE_URL}/oauth2/v1/authorize?prompt=none`,
  callbackURL: `${process.env.BASE_URL}/callback`,
  clientID: process.env.AUTH_SERVICE_CLIENT_ID,
  clientSecret: process.env.AUTH_SERVICE_CLIENT_SECRET,
  tokenURL: `${process.env.AUTH_SERVICE_BASE_URL}/oauth2/v1/token`,
});

const protected = protectRoute({ failureRedirect: '/login' });
  1. Wire up your application's login, logout, and callback routes.
server.get('/login', login);
server.get('/logout', logout, protected);
server.get('/callback', callback, (req, res) => {
  if (!req.isAuthenticated()) {
    res.redirect('/login');
    return;
  }
  res.redirect('/');
});
  1. Wire up your application's protected routes.
server.get('/', refresh, protected);
server.get('/product/*', refresh, protected);
server.get('/settings', refresh, protected);
server.all('*', (req, res) => handle(req, res));
  1. Wire up your server's GraphQL proxy route. The proxy will extract the JWT token from the session, and send it through to the GraphQL server via the Authorization header.
server.use(
  '/graphql',
  refresh,
  graphql({ baseURL: process.env.BASE_GRAPHQL_URL, isSecure: false }),
);