-
Notifications
You must be signed in to change notification settings - Fork 0
Quick Start Guide
Azizul Hakim edited this page Nov 1, 2024
·
7 revisions
After Installation nestjs-xsecurity, follow these steps to implement security in your NestJS application.
You can choose between two configuration approaches:
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { XSecurityModule } from 'nestjs-xsecurity';
@Module({
imports: [
ConfigModule.forRoot(),
XSecurityModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
enabled: config.get('XSECURITY_ENABLED', true),
secret: config.get('XSECURITY_SECRET'),
rateLimit: {
maxAttempts: config.get('XSECURITY_MAX_ATTEMPTS', 5),
decayMinutes: config.get('XSECURITY_DECAY_MINUTES', 1),
},
exclude: ['/health', '/metrics', '/api/docs/*'],
}),
}),
],
})
export class AppModule {}
import { Module } from '@nestjs/common';
import { XSecurityModule } from 'nestjs-xsecurity';
@Module({
imports: [
XSecurityModule.register({
enabled: true,
secret: process.env.XSECURITY_SECRET,
rateLimit: {
maxAttempts: 5,
decayMinutes: 1,
},
exclude: ['/health'],
}),
],
})
export class AppModule {}
Choose your preferred language for token generation:
import crypto from 'crypto';
function generateXsecurityToken(secretKey: string, expirySeconds = 300): string {
const expiryTimestamp = Math.floor(Date.now() / 1000) + expirySeconds;
const payload = { expiry: expiryTimestamp };
const token = Buffer.from(JSON.stringify(payload)).toString('base64');
const signature = crypto
.createHmac('sha256', secretKey)
.update(token)
.digest('hex');
return `${token}.${signature}`;
}
// Usage
const token = generateXsecurityToken('your-secret-key');
import hmac
import json
import base64
import hashlib
import time
def generate_xsecurity_token(secret_key: str, expiry_seconds: int = 300) -> str:
expiry = int(time.time()) + expiry_seconds
payload = {'expiry': expiry}
# Create token
token = base64.b64encode(
json.dumps(payload).encode()
).decode()
# Generate signature
signature = hmac.new(
secret_key.encode(),
token.encode(),
hashlib.sha256
).hexdigest()
return f"{token}.{signature}"
import 'dart:convert';
import 'package:crypto/crypto.dart';
String generateXsecurityToken(String secretKey, {int expirySeconds = 300}) {
final expiry = DateTime.now().millisecondsSinceEpoch ~/ 1000 + expirySeconds;
final payload = {'expiry': expiry};
final token = base64Url.encode(utf8.encode(jsonEncode(payload)));
final signature = Hmac(sha256, utf8.encode(secretKey))
.convert(utf8.encode(token))
.toString();
return '$token.$signature';
}
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.time.Instant;
import org.json.JSONObject;
public class XSecurityTokenGenerator {
public static String generateXsecurityToken(String secretKey, int expirySeconds) {
try {
// Create payload
long expiryTimestamp = Instant.now().getEpochSecond() + expirySeconds;
JSONObject payload = new JSONObject();
payload.put("expiry", expiryTimestamp);
// Encode payload
String token = Base64.getEncoder()
.encodeToString(payload.toString().getBytes(StandardCharsets.UTF_8));
// Generate signature
Mac sha256Hmac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(
secretKey.getBytes(StandardCharsets.UTF_8),
"HmacSHA256"
);
sha256Hmac.init(secretKeySpec);
String signature = bytesToHex(
sha256Hmac.doFinal(token.getBytes(StandardCharsets.UTF_8))
);
return token + "." + signature;
} catch (Exception e) {
throw new RuntimeException("Failed to generate security token", e);
}
}
private static String bytesToHex(byte[] bytes) {
StringBuilder hexString = new StringBuilder();
for (byte b : bytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
// Usage
public static void main(String[] args) {
String token = generateXsecurityToken("your-secret-key", 300);
System.out.println(token);
}
}
- See Configuration Options for detailed settings
- Check Security Best Practices for security recommendations
- Browse Token Management for advanced token handling
Copyright 2024, @AHS12 All Right Reserved