Skip to content

Network Services

Tổng quan

Gói @nx/core cung cấp IdentityNetworkService -- một HTTP client liên dịch vụ để xác thực người dùng với Identity Service. Nó kế thừa từ helper AxiosNetworkRequest của IGNIS framework và được tự động đăng ký bởi DefaultApplication.

Nguồn: packages/core/src/services/identity-network.service.ts

Xem tham chiếu IGNIS Network Helper để biết chi tiết về lớp cơ sở AxiosNetworkRequest.

Kiến trúc

Phân cấp Lớp

IdentityNetworkService

Mục đích

Giao tiếp với Identity Service cho xác thực. Vai trò chính của nó là hỗ trợ chiến lược xác thực Basic trong DefaultApplication: khi một controller sử dụng @authenticate(['basic']), thông tin xác thực được chuyển tiếp đến Identity Service thông qua service này.

Định nghĩa Lớp

typescript
import { EnvironmentKeys } from '@/common';
import { applicationEnvironment } from '@venizia/ignis';
import { AxiosNetworkRequest } from '@venizia/ignis-helpers/axios';

export class IdentityNetworkService extends AxiosNetworkRequest {
  constructor() {
    super({
      name: IdentityNetworkService.name,
      networkOptions: {
        baseUrl: applicationEnvironment.get<string>(
          EnvironmentKeys.APP_ENV_IDENTITY_SERVICE_BASE_URL,
        ),
      },
    });
  }

  async signIn(opts: {
    identifier: { scheme: string; value: string };
    credential: { scheme: string; value: string };
  }) {
    const networkService = this.getNetworkService();
    const response = await networkService.post({
      url: '/auth/sign-in',
      body: opts,
    });
    return response.data;
  }
}

Phương thức signIn

Xác thực người dùng bằng cách gửi thông tin xác thực đến endpoint /auth/sign-in của Identity Service.

Tham số:

TrườngKiểuMô tả
identifier.schemestringLoại định danh: 'username', 'email', 'phone'
identifier.valuestringGiá trị định danh (ví dụ: 'john.doe')
credential.schemestringLoại thông tin xác thực: 'basic' (mật khẩu)
credential.valuestringGiá trị thông tin xác thực (ví dụ: mật khẩu)

Trả về: Dữ liệu phản hồi từ Identity Service (ngữ cảnh người dùng với token).

Ví dụ:

typescript
const result = await identityNetworkService.signIn({
  identifier: {
    scheme: 'username',
    value: 'john.doe',
  },
  credential: {
    scheme: 'basic',
    value: 'mypassword',
  },
});

Cách DefaultApplication Sử dụng

DefaultApplication.configureSecurity() bind một hàm verifyCredentials ủy quyền cho IdentityNetworkService.signIn(). Điều này có nghĩa là bất kỳ service nào kế thừa DefaultApplication đều có thể sử dụng Basic auth mà không cần cấu hình thêm:

typescript
// Inside DefaultApplication.configureSecurity()
this.bind<IBasicTokenServiceOptions>({
  key: AuthenticateBindingKeys.BASIC_OPTIONS,
}).toValue({
  verifyCredentials: async (opts) => {
    const identityNetworkService = this.get<IdentityNetworkService>({
      key: 'services.IdentityNetworkService',
    });

    return identityNetworkService.signIn({
      identifier: { scheme: 'username', value: opts.credentials.username },
      credential: { scheme: 'basic', value: opts.credentials.password },
    });
  },
});

Luồng Xác thực

Đăng ký

IdentityNetworkService được đăng ký tự động trong DefaultApplication.configureServices():

typescript
configureServices(): void {
  this.service(IdentityNetworkService);
}

Nó được bind trong DI container với khóa services.IdentityNetworkService.

Inject trong Service Tùy chỉnh

typescript
import { inject, BaseService } from '@venizia/ignis';
import { IdentityNetworkService } from '@nx/core';

export class MyService extends BaseService {
  constructor(
    @inject({ key: 'services.IdentityNetworkService' })
    private identityNetworkService: IdentityNetworkService,
  ) {
    super({ scope: MyService.name });
  }

  async verifyUser(username: string, password: string) {
    return this.identityNetworkService.signIn({
      identifier: { scheme: 'username', value: username },
      credential: { scheme: 'basic', value: password },
    });
  }
}

Biến Môi trường

BiếnBắt buộcMô tảVí dụ
APP_ENV_IDENTITY_SERVICE_BASE_URLURL cơ sở của Identity Servicehttp://localhost:3001

Tạo Network Service Tùy chỉnh

Để giao tiếp với các service khác, hãy theo cùng mẫu:

typescript
import { EnvironmentKeys } from '@/common';
import { applicationEnvironment } from '@venizia/ignis';
import { AxiosNetworkRequest } from '@venizia/ignis-helpers/axios';

export class MyCustomNetworkService extends AxiosNetworkRequest {
  constructor() {
    super({
      name: MyCustomNetworkService.name,
      networkOptions: {
        baseUrl: applicationEnvironment.get<string>('APP_ENV_MY_SERVICE_BASE_URL'),
      },
    });
  }

  async fetchData(id: string) {
    const networkService = this.getNetworkService();
    const response = await networkService.get({ url: `/data/${id}` });
    return response.data;
  }
}

Đăng ký nó trong ứng dụng của bạn:

typescript
override configureServices(): void {
  super.configureServices();
  this.service(MyCustomNetworkService);
}

Tài liệu Liên quan

Proprietary and Confidential. Unauthorized copying, distribution, or use of this software is strictly prohibited.