Blog | G5 Cyber Security

Application Authentication

TL;DR

This guide shows how to verify requests come from your application and not someone pretending to be it. We’ll use a secret key shared between your app and your server.

1. Generate a Secret Key

You need a unique, random string that only your application and server know. This is the core of authentication. Don’t hardcode this directly into your code; store it securely (e.g., environment variables).

openssl rand -base64 32

This command creates a 32-byte random key encoded in Base64. Copy the output – this is your secret.

2. Application Sends the Key

Your application needs to include the secret key with every request it makes to your server. The best way to do this depends on how your app communicates (e.g., HTTP headers, query parameters). We’ll use an HTTP header for simplicity.

In your application code:

// Example in Python using the requests library
import requests

secret_key = "YOUR_SECRET_KEY"
headers = {"X-Application-Secret": secret_key}
response = requests.get("https://yourserver.com/api/data", headers=headers)

3. Server Verifies the Key

On your server, check that the incoming request includes the correct secret key in the expected header.

Here’s an example using Node.js with Express:

const express = require('express');
const app = express();

const validSecretKey = "YOUR_SECRET_KEY"; // Store securely!

app.get('/api/data', (req, res) => {
  const receivedSecretKey = req.headers['x-application-secret'];

  if (receivedSecretKey === validSecretKey) {
    // Key is valid - process the request
    res.send('Data access granted!');
  } else {
    // Invalid key - reject the request
    res.status(401).send('Unauthorized');
  }
});

app.listen(3000, () => console.log('Server listening on port 3000'));

4. Handling Missing Keys

Always check if the header is present *before* trying to access its value. This prevents errors.

// Node.js example:
const receivedSecretKey = req.headers['x-application-secret'];
if (!receivedSecretKey) {
  res.status(401).send('Unauthorized - Missing key');
  return;
}

5. Security Considerations

Exit mobile version