Setting up signed keys for Binance API requests in NestJS
When interacting with the Binance API using your NestJS backend, it is essential to obtain signed keys to authenticate requests and prevent unauthorized access. In this article, we will provide guidance on setting up signed keys for the /api/v3/order
and order/test
endpoints.
Why are signed keys needed?
The Binance API requires a valid API key to complete certain operations. However, by default the key is not signed, making it vulnerable to unauthorized access. To solve this problem, you will need to generate an App Secret (also known as X-Signature-Public-Key) and use it to sign your requests.
Generating signed keys
Follow these steps to get a valid signature:
- Create a Binance Developer Account: If you haven’t already, register for a Binance Developer Account.
- Generate App Secret: After logging into the developer dashboard, go to the API Key tab and click on “Generate New App Secret”. You can choose between JSON Web Token (JWT) or Server-Side Public Key Encryption (SSEK).
- Select Algorithm
: Select the appropriate algorithm for generating signed keys.
- Use App Secret in your NestJS Backend: In your NestJS application, import the
@nestjs/jwt
package and use it to create an authentication service.
Implementation example
Here is an example implementation of setting a signed key for the /api/v3/order
and order/test
endpoints using JWT:
import { Injectable } from '@nestjs/common';
import * as jwt from 'jsonwebtoken';
@Injectable()
export class AuthService {
private appSecret: string;
constructor() {
this.appSecret = process.env.BINANCE_APP_SECRET;
}
async generateToken(user: User): Promise {
const payload = {user};
return jwt.sign(payload, this.appSecret, { expiresIn: '1h' });
}
async verifyToken(token: string): Promise {
try {
const decoded = jwt.verify(token, this.appSecret);
return decoded.user as User;
} catch (error) {
return null;
}
}
async createOrder(user: User, order: OrderInput): Promise {
const token = await AuthService.generateToken(user);
const payload = {user, order };
const signature = jwt.sign(payload, this.appSecret, { expiresIn: '1h' });
return { ...order, signature };
}
}
In the example above:
- We generate a signed key using
jsonwebtoken
and store it as an environment variable.
- When creating a new order, we validate the user token with the signed key to ensure authenticity.
Putting it all together
Here is an updated version of your NestJS app that includes the signed keys:
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AuthService } from './auth.service';
@Module({
controllers: [AppController],
providers: [AuthService, AppService],
})
export class AppModule {}
“`typescript
import express from ‘express’;
import authController from ‘./auth.controller’;
import authService from ‘./auth.service’;
const app = express();
app.use(express.json());
app.post(‘/api/v3/order’, async (req: Request, res: Response) => {
const order = req.body;
try {
// Create a new order with a signed key
const token = await authService.generateToken({ user: ‘your_username’ });
const payload = { user: ‘your_username’, order};
const signature = jwt.sign(payload, ‘YOUR_APP_SECRET_KEY’);
return res.status(201).json({
message: ‘Order created successfully!’,
data: {
…order,
signature,
},
});
} catch (error) {
console.error(error);
return res.status(500).