Skip to content

Add security to API #5

Description

@chdenat
import { Elysia } from 'elysia';

const app = new Elysia();

const authorizedKeys = new Set(['clé1', 'clé2', 'clé3']); // Remplacez par vos clés API
const authorizedIPs = new Set(['192.168.1.1', '203.0.113.42']); // Remplacez par les adresses IP autorisées

app.use(async (ctx, next) => {
  const apiKey = ctx.request.headers['x-api-key'];
  const clientIP = ctx.request.ip;

  if (!apiKey || !authorizedKeys.has(apiKey) || !authorizedIPs.has(clientIP)) {
    ctx.response.status = 403;
    ctx.response.body = { error: 'Accès interdit' };
    return;
  }
  await next();
});

app.get('/votre-endpoint', (ctx) => {
  return { message: 'Accès autorisé' };
});

app.listen(3000, () => {
  console.log('Serveur en écoute sur le port 3000');
});

Activity

  1. self-assigned this
    on Aug 31, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions