The @feathersjs/authentication package provides server-side authentication through the AuthenticationService and various hooks and utilities.
Installation
npm install @feathersjs/authentication
AuthenticationService
The main authentication service that extends AuthenticationBase and implements JWT-based authentication.
Constructor
new AuthenticationService(app: Application, configKey?: string, options?: object)
The Feathers application instance
configKey
string
default:"authentication"
The configuration key name in app.get
Optional initial configuration options
Methods
create
Create and return a new JWT for a given authentication request. Triggers the login event.
service.create(
data: AuthenticationRequest,
params?: AuthenticationParams
): Promise<AuthenticationResult>
data
AuthenticationRequest
required
The authentication request (must include strategy key)interface AuthenticationRequest {
strategy?: string
[key: string]: any
}
Service call parametersinterface AuthenticationParams extends Params {
payload?: { [key: string]: any }
jwtOptions?: SignOptions
authStrategies?: string[]
secret?: string
[key: string]: any
}
The generated JWT access token
Authentication metadata including strategy and decoded payload
The authenticated entity (e.g., user object) if entity lookup is configured
Example:
const result = await app.service('authentication').create({
strategy: 'local',
email: 'user@example.com',
password: 'secret'
})
console.log(result.accessToken) // JWT token
console.log(result.user) // User object
remove
Mark a JWT as removed. By default only verifies the JWT and returns the result. Triggers the logout event.
service.remove(
id: string | null,
params?: AuthenticationParams
): Promise<AuthenticationResult>
The JWT to remove or null. When an id is passed, it must match the accessToken in params.authentication
Service call parameters with authentication information
Example:
await app.service('authentication').remove(null, {
authentication: { accessToken: 'existing-jwt-token' }
})
register
Register a new authentication strategy.
service.register(name: string, strategy: AuthenticationStrategy): void
The name to register the strategy under
strategy
AuthenticationStrategy
required
The authentication strategy instance
Example:
import { LocalStrategy } from '@feathersjs/authentication-local'
const authService = app.service('authentication')
authService.register('local', new LocalStrategy())
getStrategy
Returns a single strategy by name.
service.getStrategy(name: string): AuthenticationStrategy | undefined
createAccessToken
Create a new access token with payload and options.
service.createAccessToken(
payload: string | Buffer | object,
optsOverride?: SignOptions,
secretOverride?: Secret
): Promise<string>
payload
string | Buffer | object
required
The JWT payload
Options to extend the defaults (configuration.jwtOptions)
Use a different secret instead of the configured one
Example:
const token = await authService.createAccessToken(
{ userId: 123 },
{ expiresIn: '7d' }
)
verifyAccessToken
Verify an access token.
service.verifyAccessToken(
accessToken: string,
optsOverride?: JwtVerifyOptions,
secretOverride?: Secret
): Promise<any>
Verification optionsinterface JwtVerifyOptions extends VerifyOptions {
algorithm?: string | string[]
}
Use a different secret for verification
Example:
try {
const payload = await authService.verifyAccessToken(token)
console.log(payload) // Decoded JWT payload
} catch (error) {
console.error('Invalid token')
}
Properties
configuration
Returns the current authentication configuration.
service.configuration: AuthenticationConfiguration
Example:
const { secret, jwtOptions, authStrategies } = authService.configuration
strategyNames
A list of all registered strategy names.
service.strategyNames: string[]
Configuration
Configure authentication in your Feathers app configuration:
interface AuthenticationConfiguration {
secret: string
authStrategies: string[]
jwtOptions?: {
header?: { typ: string }
audience?: string
issuer?: string
algorithm?: string
expiresIn?: string
}
service?: string
entity?: string
entityId?: string
oauth?: object
}
The secret used to sign and verify JWTs. Keep this secure!
Array of allowed authentication strategy names
JWT signing options
header: JWT header (default: { typ: 'access' })
audience: The resource server where the token is processed
issuer: The issuing server, application or resource (default: ‘feathers’)
algorithm: Signing algorithm (default: ‘HS256’)
expiresIn: Expiration time (default: ‘1d’)
The path of the entity service (e.g., ‘users’)
The name of the entity (default: ‘user’)
The id field of the entity service. Auto-detected if not provided
Example:
// config/default.json
{
"authentication": {
"secret": "your-secret-key",
"authStrategies": ["jwt", "local"],
"jwtOptions": {
"header": { "typ": "access" },
"audience": "https://yourdomain.com",
"issuer": "feathers",
"algorithm": "HS256",
"expiresIn": "1d"
},
"service": "users",
"entity": "user"
}
}
Hooks
authenticate
Protect service methods by requiring authentication.
import { authenticate } from '@feathersjs/authentication'
authenticate(settings: string | AuthenticateHookSettings, ...strategies: string[])
settings
string | AuthenticateHookSettings
required
Strategy name(s) or settings objectinterface AuthenticateHookSettings {
service?: string
strategies?: string[]
}
Additional strategy names (when settings is a string)
Example:
// Require JWT authentication
app.service('messages').hooks({
before: {
all: [authenticate('jwt')]
}
})
// Allow multiple strategies
app.service('messages').hooks({
before: {
all: [authenticate('jwt', 'api-key')]
}
})
// With settings object
app.service('messages').hooks({
before: {
all: [
authenticate({
strategies: ['jwt'],
service: 'authentication'
})
]
}
})
JWTStrategy
The built-in JWT authentication strategy.
Configuration
interface JWTStrategyConfiguration {
header?: string
schemes?: string[]
service?: string
entity?: string
entityId?: string
}
The HTTP header to parse for the JWT
schemes
string[]
default:"['Bearer', 'JWT']"
Allowed authentication schemes
The entity service path (inherited from main auth config)
The entity name (inherited from main auth config)
The entity id field (inherited from main auth config)
Example:
import { JWTStrategy } from '@feathersjs/authentication'
authService.register('jwt', new JWTStrategy())
AuthenticationBaseStrategy
Base class for creating custom authentication strategies.
import { AuthenticationBaseStrategy } from '@feathersjs/authentication'
class CustomStrategy extends AuthenticationBaseStrategy {
async authenticate(authentication: AuthenticationRequest, params: Params) {
// Implement authentication logic
return {
authentication: { strategy: this.name },
user: { id: 1, email: 'user@example.com' }
}
}
}
Methods to Implement
authenticate
Authenticate an authentication request with this strategy.
async authenticate(
authentication: AuthenticationRequest,
params: AuthenticationParams
): Promise<AuthenticationResult>
parse (optional)
Parse a basic HTTP request for authentication information.
async parse(
req: IncomingMessage,
res: ServerResponse
): Promise<AuthenticationRequest | null>
handleConnection (optional)
Update a real-time connection according to this strategy.
async handleConnection(
event: ConnectionEvent,
connection: any,
authResult?: AuthenticationResult
): Promise<void>
Events
The authentication service emits the following events:
login
Emitted when a user successfully authenticates (after create).
app.service('authentication').on('login', (authResult, params) => {
console.log('User logged in', authResult)
})
logout
Emitted when a user logs out (after remove).
app.service('authentication').on('logout', (authResult, params) => {
console.log('User logged out', authResult)
})
Complete Example
import { feathers } from '@feathersjs/feathers'
import { AuthenticationService, JWTStrategy } from '@feathersjs/authentication'
import { LocalStrategy } from '@feathersjs/authentication-local'
const app = feathers()
// Configure authentication
app.set('authentication', {
secret: 'your-secret-key',
authStrategies: ['jwt', 'local'],
service: 'users',
entity: 'user',
jwtOptions: {
expiresIn: '7d'
},
local: {
usernameField: 'email',
passwordField: 'password'
}
})
// Set up authentication service
const authService = new AuthenticationService(app)
authService.register('jwt', new JWTStrategy())
authService.register('local', new LocalStrategy())
app.use('authentication', authService)
// Protect services
app.service('messages').hooks({
before: {
all: [authenticate('jwt')]
}
})