qqsl-encrypt
v1.0.3
Published
Angular HTTP interceptor for SM2/SM4 request and response encryption.
Maintainers
Readme
qqsl-encrypt
适用于 Angular v8-v21 的 SM2/SM4 HTTP 请求与响应加解密拦截器。
安装
npm install qqsl-encrypt业务项目需配置 SM2 公钥;需要加密请求体时,再按需配置 URL 路径关键字。protectedPathPrefixes 默认值为 [],即不加密请求参数。密钥请求头默认使用 X-Encrypted-Key,响应加密标记默认使用 X-Data-Encrypted;如服务端约定不同,可按需覆盖。
Angular v8-v14
Angular 旧版本 AOT 要求工厂函数可被静态分析,因此需要导出命名函数:
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { NgModule } from '@angular/core';
import {
createEncryptInterceptor,
EncryptInterceptor,
} from 'qqsl-encrypt';
/** 创建项目使用的接口加解密拦截器。 */
export function encryptInterceptorFactory(): EncryptInterceptor {
return createEncryptInterceptor({
protectedPathPrefixes: ['/api/user', '/api/order'],
sm2PublicKey: '服务端提供的 SM2 公钥',
});
}
@NgModule({
imports: [HttpClientModule],
providers: [
{
provide: HTTP_INTERCEPTORS,
useFactory: encryptInterceptorFactory,
multi: true,
},
],
})
export class AppModule {}Angular v15-v21
使用基于 ApplicationConfig 的启动方式时,需要启用来自依赖注入容器的拦截器:
import {
HTTP_INTERCEPTORS,
provideHttpClient,
withInterceptorsFromDi,
} from '@angular/common/http';
import { ApplicationConfig } from '@angular/core';
import {
createEncryptInterceptor,
EncryptInterceptor,
} from 'qqsl-encrypt';
/** 创建项目使用的接口加解密拦截器。 */
export function encryptInterceptorFactory(): EncryptInterceptor {
return createEncryptInterceptor({
protectedPathPrefixes: ['/api/user', '/api/order'],
sm2PublicKey: '服务端提供的 SM2 公钥',
});
}
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(withInterceptorsFromDi()),
{
provide: HTTP_INTERCEPTORS,
useFactory: encryptInterceptorFactory,
multi: true,
},
],
};行为说明
- 所有
responseType: 'json'请求都会携带X-Encrypted-Key,并支持加密响应解密。 - 请求 URL 包含任一
protectedPathPrefixes配置项时,JSON 请求体将被 SM4 加密。 FormData、Blob、空请求体和非 JSON 请求不会加密请求体。- 空字符串配置会被忽略;空数组表示不加密任何请求体。
- 未配置
protectedPathPrefixes时默认使用空数组,不加密任何请求体。 - URL 查询参数不会被加密。
- 可选配置
encryptedKeyHeader和dataEncryptedHeader,用于覆盖默认请求头和响应头名称。
