DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Secure Your Web Applications With Facial Authentication
  • What’s New in the Latest Version of Angular V15?
  • Daily 10 Tech Q&A With Bala
  • Running a Self-Hosted WAF in Production: Practical Lessons From SafeLine

Trending

  • Why Kotlin or Java Is the Wrong Question For Enterprises
  • To Switch, or Not to Switch the AI Model
  • Part 1: Building Governed MCP Tool Services With Quarkus LangChain4j and Goose
  • Moving 900+ GB of Prometheus Without a Cutover Weekend

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Software Design and Architecture
  3. Security
  4. How to Secure Your Angular Apps: End-to-End Encryption of API Calls

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.

By 
Kalyan Gottipati
·
Jul. 26, 24 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
12.2K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

When 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:

  1. Client-side encryption: Your Angular application encrypts the data with the server’s public key before transmitting it to the API. 
  2. Secure transmission: Over an HTTPS connection, the network then transmits the encrypted data. 
  3. Server-side decryption: The server decrypts the data by missioning its private key because it receives the encrypted data, seeing the original information. 
  4. Server-side encryption (Optional): Before sending the response back to the client, the server can also encrypt the data for additional security. 
  5. 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.

PowerShell
 
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.

TypeScript
 
// 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.

TypeScript
 
// 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:

JavaScript
 
// 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.

API Key management Web application AngularJS security

Opinions expressed by DZone contributors are their own.

Related

  • Secure Your Web Applications With Facial Authentication
  • What’s New in the Latest Version of Angular V15?
  • Daily 10 Tech Q&A With Bala
  • Running a Self-Hosted WAF in Production: Practical Lessons From SafeLine

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook