@uecsio/authentication-api
v1.0.0
Published
A reusable NestJS API Authentication module with JWT support
Maintainers
Readme
@uecsio/authentication-api
A reusable NestJS authentication module with JWT support for user authentication and authorization.
Features
- 🔐 JWT-based authentication
- 🛡️ Passport.js integration
- 🔑 Bcrypt password hashing
- 👤 User authentication with username/password
- 🎫 Token-based session management
- 🚀 Easy integration with TypeORM
- 📦 Standalone package - works with any NestJS application
Installation
npm install @uecsio/authentication-api @uecsio/users-apiPeer Dependencies
This package requires the following peer dependencies:
npm install @nestjs/common @nestjs/core @nestjs/jwt @nestjs/passport @nestjs/typeorm passport passport-jwt bcrypt typeorm class-validator class-transformerUsage
1. Import the Module
import { Module } from '@nestjs/common';
import { AuthenticationModule } from '@uecsio/authentication-api';
@Module({
imports: [
AuthenticationModule,
// ... other modules
],
})
export class AppModule {}2. Configuration
The module uses a default JWT secret. For production, you should override this:
Create a custom constants file or use environment variables:
// auth.config.ts
export const jwtConstants = {
secret: process.env.JWT_SECRET || 'your-secret-key',
};3. API Endpoints
Once integrated, the following endpoints are available:
POST /auth/login
Authenticate a user and receive a JWT token.
Request:
{
"username": "john_doe",
"password": "securePassword123"
}Response:
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}GET /auth/me
Get the current authenticated user's information (requires JWT token).
Headers:
Authorization: Bearer <access_token>Response:
{
"id": 1,
"username": "john_doe",
"email": "[email protected]",
"role": "admin",
"status": 1,
...
}4. Protecting Routes
Use the JwtAuthGuard to protect your routes:
import { Controller, Get, UseGuards } from '@nestjs/common';
import { JwtAuthGuard } from '@uecsio/authentication-api';
@Controller('protected')
export class ProtectedController {
@Get()
@UseGuards(JwtAuthGuard)
getProtectedData() {
return { message: 'This route is protected' };
}
}5. Getting the Current User
Access the authenticated user in your route handlers:
import { Controller, Get, Request, UseGuards } from '@nestjs/common';
import { JwtAuthGuard } from '@uecsio/authentication-api';
@Controller('profile')
export class ProfileController {
@Get()
@UseGuards(JwtAuthGuard)
getProfile(@Request() req) {
return req.user; // { userId: 1, username: 'john_doe' }
}
}API Reference
AuthenticationService
login(loginData: LoginDto): Promise<{ access_token: string }>
Authenticates a user with username and password, returns a JWT token.
getCurrentUser(userId: number): Promise<Omit<User, 'password'>>
Retrieves the current user by ID, excluding the password field.
getUserByToken(token: string): Promise<User | null>
Decodes a JWT token and retrieves the associated user.
Guards
JwtAuthGuard
Passport guard for protecting routes with JWT authentication.
DTOs
LoginDto
{
username: string; // max 255 characters
password: string; // max 255 characters
}Security Considerations
- Change the JWT Secret: Always use a strong, unique secret in production
- HTTPS Only: Use HTTPS in production to protect tokens in transit
- Token Expiration: Default token expiration is 24 hours
- Password Hashing: Passwords are automatically hashed with bcrypt
- Environment Variables: Store sensitive configuration in environment variables
Example Environment Configuration
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production
JWT_EXPIRATION=24hDependencies
This package works seamlessly with:
@uecsio/users-api- User management module- TypeORM - Database ORM
- Passport.js - Authentication middleware
- JWT - JSON Web Tokens
License
MIT
Author
Dmytro Morozov [email protected]
