Grant Koa OAuth Proxy Middleware
raw JSON → 5.4.8 verified Thu Apr 23 auth: no javascript
grant-koa is a specialized middleware designed to integrate the Grant OAuth Proxy into Koa.js applications. It abstracts the complexities of OAuth and OpenID Connect flows, providing a unified interface for authenticating users against various identity providers (e.g., Google, GitHub, Facebook). The current stable version is 5.4.8. As an adapter for the core `grant` library, its release cadence is generally tied to updates in `grant` and compatibility with major Koa versions. This package is crucial for Koa developers needing to implement robust and flexible authentication/authorization without deep diving into each OAuth provider's specific API, offering a streamlined approach to secure user access and data.
Common errors
error TypeError: app.use() expects a middleware function ↓
cause The `grant` instance was not called as a function, or `koa-session` was not initialized correctly before `grant-koa`.
fix
Ensure
const grant = Grant(grantConfig); is correctly assigning the middleware function, and that app.use(session({}, app)); is present and correctly configured before app.use(grant);. error OAuth error: redirect_uri_mismatch ↓
cause The configured `callback` URL in `grantConfig` does not precisely match the redirect URI registered in the OAuth provider's application settings (e.g., Google Console).
fix
Verify that the
origin and callback properties in your grantConfig exactly match the redirect URI registered with your OAuth provider, including protocol (http/https), hostname, port, and path. error Error: Grant: missing or invalid credentials for [provider] ↓
cause The `key` (client ID) or `secret` (client secret) for an OAuth provider in the `grantConfig` is missing or incorrect.
fix
Ensure
process.env.YOUR_PROVIDER_CLIENT_ID and process.env.YOUR_PROVIDER_CLIENT_SECRET are correctly set in your environment variables and that grantConfig is referencing them or providing valid hardcoded values. Warnings
breaking Koa v3 removed support for generator functions, requiring all middleware to be `async/await`. Ensure your application and any other middleware are compatible with Koa v2+ (which `grant-koa` is designed for) and avoid generator-based middleware if upgrading Koa. ↓
fix Migrate any custom generator-based Koa middleware to async/await functions. `grant-koa` itself uses async/await internally, but userland middleware might need updates.
gotcha `grant-koa` relies heavily on Koa's session middleware (`koa-session` or similar) to store transient OAuth state and tokens. Forgetting to configure or properly `app.use()` a session middleware *before* `grant-koa` will lead to authentication failures and errors. ↓
fix Always ensure `koa-session` (or an equivalent) is installed and used as `app.use(session({}, app));` prior to `app.use(grant);`.
gotcha Incorrect `origin` or `callback` URLs in the `grantConfig` can cause 'redirect_uri_mismatch' errors with OAuth providers. These must exactly match the URLs registered with the OAuth provider. ↓
fix Double-check that `grantConfig.defaults.origin` and the `callback` URL specified for each provider (e.g., `google.callback`) precisely match the configured redirect URIs in your OAuth provider's developer console. Ensure 'http' vs 'https' and trailing slashes match.
deprecated Older versions of `grant` (and thus `grant-koa` implicitly) might use less secure defaults or older OAuth specifications. Always refer to the latest `grant` documentation for security best practices, especially regarding `state` and `pkce` parameters. ↓
fix Upgrade to the latest stable version of `grant` and `grant-koa`. Review the `grant` configuration options for `state: true` and `pkce: true` (if supported by the provider) to enhance security against CSRF and authorization code interception attacks.
Install
npm install grant-koa yarn add grant-koa pnpm add grant-koa Imports
- grant wrong
const grant = require('grant-koa');correctimport grant from 'grant-koa'; // or import Grant from 'grant-koa'; - GrantMiddleware
import Grant, { GrantMiddleware } from 'grant-koa'; // Used for type hinting in TypeScript - Koa context typing
import { Context } from 'koa'; interface CustomContext extends Context { session: Record<string, any>; // ... potentially other grant-specific properties }
Quickstart
import Koa from 'koa';
import Router from '@koa/router';
import session from 'koa-session';
import Grant from 'grant-koa';
const app = new Koa();
const router = new Router();
// Koa session is required by grant-koa
app.keys = ['your-secret-session-key']; // Replace with a strong secret
app.use(session({}, app));
const grantConfig = {
defaults: {
origin: 'http://localhost:3000',
transport: 'session',
state: true,
},
google: {
key: process.env.GOOGLE_CLIENT_ID ?? 'YOUR_GOOGLE_CLIENT_ID',
secret: process.env.GOOGLE_CLIENT_SECRET ?? 'YOUR_GOOGLE_CLIENT_SECRET',
scope: ['openid', 'profile', 'email'],
callback: '/connect/google/callback',
},
};
// Initialize Grant middleware
const grant = Grant(grantConfig);
app.use(grant as Koa.Middleware); // Type assertion might be needed depending on Koa version/types
// OAuth initiation route
router.get('/connect/google', async (ctx) => {
ctx.redirect('/connect/google'); // Redirects to grant-koa for OAuth flow
});
// OAuth callback route
router.get('/connect/google/callback', async (ctx) => {
if (ctx.session?.grant?.response?.access_token) {
ctx.body = `Hello, your Google access token is: ${ctx.session.grant.response.access_token}`;
} else {
ctx.body = 'Authentication failed or cancelled.';
}
});
app.use(router.routes()).use(router.allowedMethods());
app.listen(3000, () => {
console.log('Koa app listening on http://localhost:3000');
console.log('Initiate Google OAuth by visiting http://localhost:3000/connect/google');
});