Package Exports
- oauth2-pkce-client
Readme
OAuth2 PKCE Client
A secure, lightweight OAuth2 Authorization Code Flow with PKCE (Proof Key for Code Exchange) implementation for modern web applications.
Features
- ๐ Secure by Default: Implements OAuth2 Authorization Code Flow with PKCE
- ๐ Lightweight: Zero runtime dependencies, < 10KB gzipped
- โ๏ธ React Support: Built-in React hooks and context provider
- ๐ Auto Token Refresh: Automatic token refresh before expiry
- ๐ฆ TypeScript: Full TypeScript support with type definitions
- ๐ณ Tree-shakeable: Import only what you need
- ๐งช Well Tested: Comprehensive test coverage
- ๐ฏ Framework Agnostic: Works with any JavaScript framework
Installation
npm install oauth2-pkce-client
# or
yarn add oauth2-pkce-client
# or
pnpm add oauth2-pkce-client
Quick Start
Vanilla JavaScript
import { OAuth2Service } from 'oauth2-pkce-client';
const oauth = new OAuth2Service({
clientId: 'your-client-id',
authorizationEndpoint: 'https://auth.example.com/authorize',
tokenEndpoint: 'https://auth.example.com/token',
redirectUri: 'http://localhost:3000/callback',
scope: 'openid profile email',
});
// Start login
await oauth.authorize();
// Handle callback (automatically called on redirect URI)
// Tokens are automatically stored
// Check authentication
if (oauth.isAuthenticated()) {
const token = oauth.getAccessToken();
// Use token for API calls
}
// Logout
oauth.logout();
React
import { OAuth2Provider, useAuth } from 'oauth2-pkce-client';
// Wrap your app with OAuth2Provider
function App() {
const config = {
clientId: 'your-client-id',
authorizationEndpoint: 'https://auth.example.com/authorize',
tokenEndpoint: 'https://auth.example.com/token',
redirectUri: 'http://localhost:3000/callback',
scope: 'openid profile email',
};
return (
<OAuth2Provider config={config}>
<YourApp />
</OAuth2Provider>
);
}
// Use the auth hook in components
function LoginButton() {
const { isAuthenticated, login, logout, getToken } = useAuth();
if (isAuthenticated) {
return <button onClick={() => logout()}>Logout</button>;
}
return <button onClick={() => login()}>Login</button>;
}
API Reference
OAuth2Service
The main class for handling OAuth2 authentication.
Constructor
new OAuth2Service(config: OAuth2Config)
Configuration Options
Option | Type | Required | Description |
---|---|---|---|
clientId |
string | โ | OAuth2 client ID |
authorizationEndpoint |
string | โ | Authorization server's authorize endpoint |
tokenEndpoint |
string | โ | Authorization server's token endpoint |
redirectUri |
string | โ | Redirect URI registered with OAuth2 provider |
scope |
string | โ | Space-delimited list of scopes |
logoutEndpoint |
string | โ | Optional logout endpoint |
autoRefresh |
boolean | โ | Enable automatic token refresh (default: true) |
refreshBufferTime |
number | โ | Seconds before expiry to refresh (default: 300) |
storage |
Storage | โ | Custom storage implementation (default: localStorage) |
debug |
boolean | โ | Enable debug logging |
Methods
authorize(additionalParams?)
: Start the authorization flowhandleCallback(url?)
: Handle OAuth2 callback (called automatically)refreshAccessToken()
: Manually refresh the access tokengetAccessToken()
: Get current access tokengetRefreshToken()
: Get current refresh tokengetIdToken()
: Get ID token (if available)isAuthenticated()
: Check if user is authenticatedgetAuthState()
: Get complete authentication statelogout(redirectTo?)
: Logout user
React Hooks
useOAuth2
const {
isAuthenticated,
isLoading,
accessToken,
refreshToken,
error,
login,
logout,
refreshToken,
getToken,
} = useOAuth2(config);
useAuth
Must be used within OAuth2Provider
:
const auth = useAuth();
Advanced Usage
Custom Storage
import { OAuth2Service } from 'oauth2-pkce-client';
const oauth = new OAuth2Service({
// ... other config
storage: sessionStorage, // Use sessionStorage instead of localStorage
});
Additional Authorization Parameters
// Pass additional parameters to the authorization request
await oauth.authorize({
prompt: 'consent',
login_hint: 'user@example.com',
});
Token Refresh Callbacks
const oauth = new OAuth2Service({
// ... other config
onTokenRefresh: (tokens) => {
console.log('Tokens refreshed:', tokens);
},
onAuthStateChange: (isAuthenticated) => {
console.log('Auth state changed:', isAuthenticated);
},
});
Security Considerations
This library implements several security best practices:
- PKCE (RFC 7636): Protects against authorization code interception attacks
- State Parameter: Prevents CSRF attacks
- Secure Token Storage: Tokens stored in configurable storage (localStorage/sessionStorage)
- Automatic Token Expiry: Tokens are automatically cleared when expired
- XSS Protection: No tokens in URLs or global scope
Browser Support
- Chrome/Edge 91+
- Firefox 89+
- Safari 15+
- Opera 77+
Requires native Crypto API support for PKCE.
Contributing
Contributions are welcome! Please read our Contributing Guide for details.
License
MIT ยฉ Jeremy Walters