How To Secure Your Angular Apps: End-To-End Encryption of API Calls
Explore an example of implementing end-to-end encryption of API calls in your secure web app built with Angular.
Join the DZone community and get the full member experience.
Join For FreeWhen it comes to secure web applications, we must keep sensitive data secure during the communication period. Sadly, while HTTPS encrypts data as it moves from point A to point B, the information is still exposed in a browser's network tab and can leak out this way. In this post, I will give you an example of implementing end-to-end encryption of API calls in your secure web app built with Angular.
Encryption Workflow
Weak protections have traditionally been obfuscation with Base64 encoding or custom schemes. Public key cryptography (PKC) is considered a modern solution to be more secure. It uses a key pair one public key for encryption, and the other private key for decryption. A public key is distributed and a private key is kept on the server.
The encryption workflow is as follows:
- Client-side encryption: Your Angular application encrypts the data with the server’s public key before transmitting it to the API.
- Secure transmission: Over an HTTPS connection, the network then transmits the encrypted data.
- Server-side decryption: The server decrypts the data by missioning its private key because it receives the encrypted data, seeing the original information.
- Server-side encryption (Optional): Before sending the response back to the client, the server can also encrypt the data for additional security.
- Client-side decryption: Finally, the client decrypts the encrypted response from the server using a public key stored in the web application.
Implementation Into Angular App
Here is a detailed strategy to implement end-to-end encryption in your Angular financial app.
1. Library Selection and Installation
Choose a well-maintained library like Angular CryptoJS or Sodium for JavaScript, but still put more reliance than loafing in trying to implement them. These libraries contain the APIs for encryption and decryption which is provided by multiple algorithms.
npm install crypto-js
2. Key Management
Implement a feature to keep the server's public key safe. There are a couple of common approaches to this:
- Server-side storage: One relatively simple solution is to store the public key on your backend server, and then retrieve it during application initialization in Angular via an HTTPS request.
- Key Management Service (Optional): For more advanced set ups, consider a KMS dedicated to secret management, but this requires an extra layer.
3. Create Client-Side Encryption and Decryption Service
Create a common crypto service to handle the application data encryption and decryption.
// src/app/services/appcrypto.service.ts
import { Injectable } from '@angular/core';
import * as CryptoJS from 'crypto-js';
@Injectable({
providedIn: 'root'
})
export class AppCryptoService {
private appSerSecretKey: string = 'server-public-key';
encrypt(data: any): string {
return CryptoJS.AES.encrypt(JSON.stringify(data), this.appSerSecretKey).toString();
}
decrypt(data: string): any {
const bytes = CryptoJS.AES.decrypt(data, this.appSerSecretKey);
return JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
}
}
4. Application API Call Service
Create a common service to handle the web application's common HTTP methods.
// src/app/services/appcommon.service.ts
import { Injectable, Inject } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { AppCryptoService } from '../services/crypto.service';
@Injectable({
providedIn: 'root'
})
export class AppCommonService {
constructor(private appCryptoService: AppCryptoService
private httpClient: HttpClient) {}
postData(url: string, data: any): Observable<any> {
const encryptedData = this.appCryptoService.encrypt(data);
return this.httpClient.post(url, encryptedData);
}
}
5. Server-Side Decryption
On the server side, you have to decrypt all incoming request payloads and encrypt response payloads. Here's an example using Node. js and Express:
// server.js
const express = require('express');
const bodyParser = require('body-parser');
const crypto = require('crypto-js');
const app = express();
const secretKey = 'app-secret-key';
app.use(bodyParser.json());
// Using middleware to decrypt the incoming request bodies
app.use((req, res, next) => {
if (req.body && typeof req.body === 'string') {
const bytes = crypto.AES.decrypt(req.body, secretKey);
req.body = JSON.parse(bytes.toString(crypto.enc.Utf8));
}
next();
});
// Test post route call
app.post('/api/data', (req, res) => {
console.log('Decrypted data:', req.body);
// response object
const responseObj = { message: 'Successfully received' };
// Encrypt the response body (Optional)
const encryptedResBody = crypto.AES.encrypt(JSON.stringify(responseBody), secretKey).toString();
res.send(encryptedResBody);
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
6. Server-Side Encryption (Optional)
The response of the server can also be sent back to the client in an encrypted form for security. This does add a layer of security, though with the caveat that it may impact system performance.
7. Client-Side Decryption (Optional)
When the response is encrypted from the server, decrypt it on the client side.
Conclusion
This example keeps it simple by using AES encryption. You may want additional encryption mechanisms, depending on your security needs. Don't forget to manage errors and exceptions properly. This is a somewhat crude implementation of encryption in your Angular web app when making API calls around.
Opinions expressed by DZone contributors are their own.
Comments