JWT-based authentication with automatic token management, storage, and header population for secure API communication across all transport methods.
Configure the application with authentication capabilities including token management and automatic header population.
/**
* Configure authentication for the application
* @param options - Optional authentication configuration
* @returns Configuration function for the application
*/
function authentication(options?: Partial<AuthenticationClientOptions>): (app: Application) => void;
interface AuthenticationClientOptions {
/** Header name for authentication token (default: 'Authorization') */
header: string;
/** Authentication scheme (default: 'Bearer') */
scheme: string;
/** Storage key for JWT token (default: 'feathers-jwt') */
storageKey: string;
/** URL parameter key for token (default: 'access_token') */
locationKey: string;
/** URL parameter key for errors (default: 'error') */
locationErrorKey: string;
/** JWT strategy name (default: 'jwt') */
jwtStrategy: string;
/** Authentication service path (default: '/authentication') */
path: string;
/** Token storage implementation */
storage: Storage;
}Usage Example:
import feathers from "@feathersjs/client";
import { authentication } from "@feathersjs/client";
const app = feathers();
// Configure with default options
app.configure(authentication());
// Configure with custom options
app.configure(authentication({
header: "X-Auth-Token",
scheme: "JWT",
storageKey: "my-app-token",
path: "/auth"
}));Methods added to the application instance for managing authentication state.
/**
* Authenticate user with credentials
* @param data - Authentication request data (strategy, credentials)
* @param params - Optional request parameters
* @returns Promise resolving to authentication result with token
*/
authenticate(data?: AuthenticationRequest, params?: Params): Promise<AuthenticationResult>;
/**
* Re-authenticate using stored token
* @param force - Force re-authentication even if token exists
* @param strategy - Strategy name (default: 'jwt')
* @param params - Optional request parameters
* @returns Promise resolving to authentication result
*/
reAuthenticate(force?: boolean, strategy?: string, params?: Params): Promise<AuthenticationResult>;
/**
* Log out and clear authentication state
* @returns Promise resolving to logout result or null
*/
logout(): Promise<AuthenticationResult | null>;
/** Authentication client instance */
authentication: AuthenticationClient;Usage Examples:
// Authenticate with username/password
const authResult = await app.authenticate({
strategy: "local",
email: "user@example.com",
password: "password123"
});
console.log("Access token:", authResult.accessToken);
console.log("User:", authResult.user);
// Re-authenticate with stored token
const reAuthResult = await app.reAuthenticate();
// Force re-authentication
const forceAuthResult = await app.reAuthenticate(true);
// Log out
await app.logout();Direct token management methods for advanced use cases.
/**
* Store access token in configured storage
* @param token - JWT access token to store
* @returns Promise completing when token is stored
*/
setAccessToken(token: string): Promise<void>;
/**
* Retrieve stored access token
* @returns Promise resolving to stored token or null if not found
*/
getAccessToken(): Promise<string | null>;
/**
* Remove stored access token
* @returns Promise completing when token is removed
*/
removeAccessToken(): Promise<void>;
/**
* Extract token from URL location (for OAuth redirects)
* @param location - URL location object
* @returns Promise resolving to extracted token or null
*/
getFromLocation(location: Location): Promise<string | null>;Usage Examples:
// Manual token management
await app.authentication.setAccessToken("eyJhbGciOiJIUzI1NiIs...");
const token = await app.authentication.getAccessToken();
console.log("Stored token:", token);
// Remove token
await app.authentication.removeAccessToken();
// Extract token from OAuth redirect
const urlToken = await app.authentication.getFromLocation(window.location);
if (urlToken) {
await app.authentication.setAccessToken(urlToken);
}Hooks for automatic authentication and header population in service calls.
/**
* Hook for automatic authentication on service calls
* @returns Hook function that adds authentication to requests
*/
function authentication(): HookFunction;
/**
* Hook for populating JWT header on service requests
* @returns Hook function that adds Authorization header
*/
function populateHeader(): HookFunction;Usage Examples:
import { authentication, populateHeader } from "@feathersjs/client";
// Use authentication hook on specific service
const userService = app.service("users");
userService.hooks({
before: {
all: [authentication()]
}
});
// Use header population hook
userService.hooks({
before: {
all: [populateHeader()]
}
});
// Application-level hooks for all services
app.hooks({
before: {
all: [authentication(), populateHeader()]
}
});Token storage implementations for different environments.
interface Storage {
getItem(key: string): Promise<string | null> | string | null;
setItem(key: string, value: string): Promise<void> | void;
removeItem(key: string): Promise<void> | void;
}
/**
* In-memory storage implementation (default for Node.js)
*/
class MemoryStorage implements Storage {
getItem(key: string): string | null;
setItem(key: string, value: string): void;
removeItem(key: string): void;
}
/**
* localStorage wrapper (default for browsers)
*/
class StorageWrapper implements Storage {
constructor(storage: any);
getItem(key: string): string | null;
setItem(key: string, value: string): void;
removeItem(key: string): void;
}
// Additional Storage implementations
class AsyncStorage implements Storage {
getItem(key: string): Promise<string | null>;
setItem(key: string, value: string): Promise<void>;
removeItem(key: string): Promise<void>;
}Usage Examples:
// Custom storage implementation
class CustomStorage implements Storage {
async getItem(key: string): Promise<string | null> {
// Custom retrieval logic
return localStorage.getItem(key);
}
async setItem(key: string, value: string): Promise<void> {
// Custom storage logic
localStorage.setItem(key, value);
}
async removeItem(key: string): Promise<void> {
// Custom removal logic
localStorage.removeItem(key);
}
}
// Use custom storage
app.configure(authentication({
storage: new CustomStorage()
}));Support for OAuth flows and third-party authentication providers.
Usage Examples:
// OAuth authentication
const authResult = await app.authenticate({
strategy: "google",
// OAuth provider will handle the authentication flow
});
// GitHub authentication
const githubAuth = await app.authenticate({
strategy: "github"
});
// Custom authentication strategy
const customAuth = await app.authenticate({
strategy: "custom-ldap",
username: "user",
password: "pass"
});interface AuthenticationRequest {
strategy: string;
[key: string]: any;
}
interface AuthenticationResult {
accessToken?: string;
authentication?: {
strategy: string;
accessToken?: string;
payload?: any;
};
user?: any;
[key: string]: any;
}
interface AuthenticationClient {
options: AuthenticationClientOptions;
app: Application;
authenticated: boolean;
service: Service;
storage: Storage;
setAccessToken(token: string): Promise<void>;
getAccessToken(): Promise<string | null>;
removeAccessToken(): Promise<void>;
getFromLocation(location: Location): Promise<string | null>;
handleError(error: any, type: string): Promise<any>;
handleSocket(socket: any): void;
reset(): Promise<null>;
}
interface Location {
protocol: string;
host: string;
hostname: string;
port: string;
pathname: string;
search: string;
hash: string;
href: string;
}