You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 12如何实现URL掩码 隐藏真实路由生成动态加密URL

Angular实现加密隐藏真实路由路径的方案

核心逻辑是建立真实业务路由和随机加密串的映射关系,跳转时生成加密串作为URL路径,路由解析层负责解密后匹配真实路由渲染内容,全程不暴露真实路由路径到浏览器地址栏。

1. 实现路由加解密工具类

封装加解密方法,支持拼接时间戳防重放、防篡改,示例采用Base64混淆+自定义密钥校验,生产环境可替换为安全性更高的AES对称加密:

// utils/route-crypto.util.ts
export class RouteCryptoUtil {
  // 加密密钥建议通过环境变量注入,不要硬编码在前端源码中
  private static readonly SECRET_KEY = 'YOUR_CUSTOM_ENCRYPT_KEY';
  // 加密串有效期,示例为24小时
  private static readonly EXPIRE_TIME = 24 * 60 * 60 * 1000;

  // 传入真实路由路径,生成符合URL规范的加密串
  static encrypt(realPath: string): string {
    const timeStamp = Date.now().toString();
    const rawContent = `${realPath}|${timeStamp}|${this.SECRET_KEY}`;
    // Base64编码后做URI编码,避免特殊字符导致路由解析异常
    return encodeURIComponent(btoa(rawContent));
  }

  // 解析加密串,返回合法的真实路由路径,非法/过期串返回null
  static decrypt(encryptedStr: string): string | null {
    try {
      const rawContent = atob(decodeURIComponent(encryptedStr));
      const [realPath, timeStamp, verifyKey] = rawContent.split('|');
      // 校验密钥合法性和加密串有效期
      if (verifyKey !== this.SECRET_KEY || Date.now() - Number(timeStamp) > this.EXPIRE_TIME) {
        return null;
      }
      return realPath;
    } catch (error) {
      return null;
    }
  }
}

2. 配置路由规则

根路由表只配置公开路由和通配解析路由,真实业务路由单独存放在不对外暴露的私有路由配置文件中:

// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LoginComponent } from './components/login/login.component';
import { NotFoundComponent } from './components/not-found/not-found.component';
import { RouteResolverComponent } from './components/route-resolver/route-resolver.component';

const routes: Routes = [
  // 公开路由,不需要加密处理
  { path: 'login', component: LoginComponent },
  { path: '404', component: NotFoundComponent },
  // 通配路由,所有加密路径统一走解析逻辑
  { path: '**', component: RouteResolverComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

3. 实现路由解析逻辑

通过专用的解析组件处理加密路径,解密后匹配真实路由,渲染对应业务组件时不修改浏览器地址栏:

// components/route-resolver/route-resolver.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { RouteCryptoUtil } from '../../utils/route-crypto.util';
// 私有业务路由配置表,格式和普通路由配置一致,示例:[{path: 'Product/Category', component: ProductCategoryComponent}]
import { PRIVATE_ROUTES } from '../../config/private-routes.config';

@Component({
  template: `<router-outlet></router-outlet>`
})
export class RouteResolverComponent implements OnInit {
  constructor(
    private activeRoute: ActivatedRoute,
    private router: Router
  ) {}

  ngOnInit(): void {
    const encryptedPath = this.activeRoute.snapshot.url[0]?.path;
    if (!encryptedPath) {
      this.router.navigate(['/404']);
      return;
    }

    const realPath = RouteCryptoUtil.decrypt(encryptedPath);
    if (!realPath) {
      this.router.navigate(['/404']);
      return;
    }

    const matchedRoute = PRIVATE_ROUTES.find(route => route.path === realPath);
    if (matchedRoute) {
      // skipLocationChange参数保证渲染组件时不修改浏览器地址栏
      this.router.navigate([realPath], { skipLocationChange: true });
    } else {
      this.router.navigate(['/404']);
    }
  }
}

4. 调整页面跳转逻辑

所有业务页面跳转不直接使用真实路由路径,调用加密方法生成加密串后再跳转:

// 错误用法:直接跳转真实路径,会暴露路由信息
// this.router.navigate(['/Product/Category']);

// 正确用法:生成加密路径后跳转,地址栏显示加密串
const encryptedPath = RouteCryptoUtil.encrypt('Product/Category');
this.router.navigate([`/${encryptedPath}`]);

可选优化方案

  • 路由带参数的场景可将参数拼接在加密内容中,解密后拆分传入路由即可
  • 安全性要求高的场景可将加密映射关系存在后端,前端解析加密串前先请求后端校验合法性
  • 加密串过期后可自动刷新生成新的有效串,避免路由地址被泄露复用

内容的提问来源于stack exchange,提问作者Zulfikar Badurdeen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 01:36:03