Secure transmission of sensitive information in session tokens
import express from 'express';
const app = express();
app.get('/login', (req, res) => {
const sessionToken = req.query.token;
// Perform authentication logic here
res.send('Login successful');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
The vulnerability in the provided code is that it sends the session token as a query parameter in the URL. This means that the session token is visible in the URL and can be cached by the browsing history. If an attacker gains local access to the machine, they can easily obtain the session token from the browsing history and use it to impersonate the user's session.
In the code, the session token is retrieved from the URL using the
req.query.token
statement. This allows anyone with access to the URL to see and potentially intercept the session token.
To mitigate this vulnerability, it is recommended to use secure mechanisms to send sensitive information between sites. One common approach is to use HTTP headers or request bodies to transmit sensitive data instead of including it in the URL. Additionally, it is important to ensure that the session token is properly encrypted and protected during transmission.
import express from 'express';
const app = express();
app.use(express.json());
app.post('/login', (req, res) => {
const sessionToken = req.body.token;
// Perform authentication logic here
res.send('Login successful');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
The fixed code is written in TypeScript and uses the Express framework to handle HTTP requests. It addresses the vulnerability by not sending sensitive information, specifically the session token, via URL parameters.
The code sets up an Express server and configures it to parse incoming JSON data using the
express.json()
middleware. This allows the server to handle JSON payloads in the request body.
The
/login
route is defined as a POST request handler. When a POST request is made to this route, the server expects a JSON payload in the request body, which should contain the session token. The code retrieves the session token from
req.body.token
and performs the authentication logic.
If the authentication is successful, the server sends a response with the message "Login successful" using the
res.send()
method.
The server listens on port 3000 using the
app.listen()
method, and a message is logged to the console to indicate that the server is running.
By using the request body to send the session token instead of URL parameters, the sensitive information is not exposed in the URL and cannot be cached by the browsing history. This helps prevent attackers with local access to the machine from obtaining the session token.