@lightspeed/next-auth
v0.1.4
Published
Auth integration with Next.js
Downloads
18
Keywords
Readme
@lightspeed/next-auth
Introduction
Libraries for easily integrating an OAuth2 flow with your Next.js
application.
Quick Start
- Install the required dependencies in your webapp.
yarn add @lightspeed/next-auth express-session body-parser uid-safe
- 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,
}),
);
- 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' });
- 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('/');
});
- 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));
- 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 }),
);