Analyzing Angular local storage from a security perspective

As web applications continue to grow, front-end developers slowly realize that using the local storage technology provided by browsers can conveniently save application data without using an external database. As one of the most popular front-end frameworks, Angular also provides support for many local storage technologies in its API. However, security concerns also become more important when using local storage. Therefore, this article will introduce how to use local storage in Angular applications from a security perspective, and provide some examples.

What is local storage?

Local storage refers to storing data on the client (that is, the user's computer memory or file system) rather than on the server. With local storage, you can access cached data faster, reduce server pressure, and improve user experience. Common local storage technologies include cookies, Web Storage API, and IndexedDB.

Local storage techniques in Angular

Cookie

In Angular, ngx-cookie-serviceit is easy to read and write cookies through libraries. However, since cookies are automatically sent to the server with each request, unencrypted sensitive information may be stolen, causing security issues.

Web Storage API

Web Storage API is divided into two types: localStorage and sessionStorage, they can only store string type data, but have good scalability and reliability. Usually, we use or @angular/commonin the library to read and write to Web Storage.LocalStorageServiceSessionStorageService

LocalStorage

LocalStorage is similar to Cookie, but the biggest difference of LocalStorage is that it is not automatically sent to the server with each request, but is completely controlled by the browser. When using LocalStorage, you need to pay attention to the following points:

  • Only necessary information should be stored
  • Never store unencrypted sensitive information in LocalStorage
  • Clear useless data in time

The following is an LocalStorageServiceexample of using stored user information:

import {
    
     Component, OnInit } from '@angular/core';
import {
    
     LocalStorageService } from 'ngx-webstorage';

@Component({
    
    
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {
    
    
  currentUser: any;
  constructor(private localStorage: LocalStorageService) {
    
     }

  ngOnInit(): void {
    
    
    this.currentUser = this.localStorage.retrieve('currentUser');
  }

  login() {
    
    
    // 在此处完成用户登录操作
    this.currentUser = {
    
     name: 'John', age: 30 };
    this.localStorage.store('currentUser', this.currentUser);
  }

  logout() {
    
    
    this.localStorage.clear('currentUser');
  }
}

SessionStorage

SessionStorage is similar to LocalStorage, but the data of SessionStorage is only valid during the current session. In Angular, using SessionStorageServicecan easily handle SessionStorage read and write operations.

IndexedDB

IndexedDB allows offline access, efficient storage, and high-performance retrieval of data. In Angular, ng-idbobject storage in IndexedDB can be easily created and managed using the library.

Local Storage Instance from a Security Perspective

Step 1: Introduce localStorageService

In Angular, you can use the third-party library "angular-local-storage" to operate local storage. Install it into your project via the following command line:

npm install angular-local-storage

Then import the library in components or services that need to use localStorage:

import {
    
     LocalStorageService } from 'angular-local-storage';

Step 2: Set a security prefix

Any experienced hacker knows that if local storage is not secured properly, they can modify the data stored in the browser and completely break your application. To prevent this from happening, it is best to add a safe prefix to localStorage.

export class ExampleComponent {
    
    
  prefix = "myapp_"; // 设置一个安全前缀
  private dataKey = `${
      
      this.prefix}data_key`;

  constructor(private localStorage: LocalStorageService) {
    
    }

  setData(data: any): void {
    
    
    this.localStorage.set(this.dataKey, data);
  }

  getData(): any {
    
    
    return this.localStorage.get(this.dataKey);
  }

  removeData(): void {
    
    
    this.localStorage.remove(this.dataKey);
  }
}

In the code sample above, we created a prefix and a dataKey which will store our actual data in local storage. In addition, we have written three methods for manipulating the data. The setData() method writes data into LocalStorage, the getData() method retrieves the data and returns it, and the removeData() method removes the data from localStorage.

Step Three: Encrypt Sensitive Data

All the more so if the data you handle is sensitive, you should take extra steps to ensure its security. You can use modern encryption technology like AES encryption algorithm to encrypt the data you write, and then decrypt it in the program. In this case, the data stored locally will be unreadable.

Here is an example:

import * as CryptoJS from 'crypto-js';

export class ExampleComponent {
    
    
  static readonly keySize = 256;
  static readonly ivSize = 128;

  private secretKey = CryptoJS.lib.WordArray.random(ExampleComponent.keySize / 8).toString(CryptoJS.enc.Hex);
  private iv = CryptoJS.lib.WordArray.random(ExampleComponent.ivSize / 8).toString(CryptoJS.enc.Hex);
  private dataKey = `${
      
      this.prefix}data_key`;

  constructor(private localStorage: LocalStorageService) {
    
    }

  setData(data: any): void {
    
    
    const encryptedData = CryptoJS.AES.encrypt(JSON.stringify(data), this.secretKey, {
    
     iv: this.iv }).toString();
    this.localStorage.set(this.dataKey, encryptedData);
  }

  getData(): any {
    
    
    const encryptedData = this.localStorage.get(this.dataKey);
    if (encryptedData) {
    
    
      const decryptedData = CryptoJS.AES.decrypt(encryptedData, this.secretKey, {
    
     iv: this.iv });
      return JSON.parse(decryptedData.toString(CryptoJS.enc.Utf8));
    } else {
    
    
      return null;
    }
  }

  removeData(): void {
    
    
    this.localStorage.remove(this.dataKey);
  }
}

In the above code example, we use the CryptoJS encryption library for encryption and decryption. In the setData() method, we stringify the data to be stored, encrypt it with AES, and store it in local storage. In the getData() method, we get the encrypted data and decrypt it, and finally return the decrypted original data. In the removeData() method, we delete data without decryption.

The above are some suggestions for analyzing Angular local storage from the perspective of security, I hope it will be helpful to you. If you have any other questions or doubts, please leave a message.

Guess you like

Origin blog.csdn.net/lin5165352/article/details/132271006