NestJS OAuth2 服务器
安装
安装和运行一样简单 :
npm install @boyuai/nestjs-oauth2-server
或者说
yarn add @boyuai/nestjs-oauth2-server。 。 。 .
配置
- 将模块作为依赖性纳入将发生oauth的模块:
oauth2.module.ts
import { Module } from '@nestjs/common';
import { OAuth2ServerModule } from '@boyuai/nestjs-oauth2-server';
import { OAuth2Controller } from './oauth2.controller';
import { OAuth2ServiceModule } from './oauth2-service.module';
import { OAuth2Model } from './oauth2.model';
@Module({
imports: [
OAuth2ServiceModule,
OAuth2ServerModule.forRoot({
imports: [OAuth2ServiceModule], // import your repository for OAuth2Model here
modelClass: OAuth2Model,
}),
],
controllers: [OAuth2Controller],
})
export class OAuth2Module {}
除了上述, oaut2 服务器 需要一个 模式 创建服务器。 这可作为申请的任何部分提供的服务。 这应能获取客户端、用户、信使和授权代码的数据。 这个 必须 成为装饰于 Injectable 装饰师.
oauth2.model.ts
import { Injectable } from '@nestjs/common';
@Injectable()
export class OAuth2Model implements RequestAuthenticationModel {
getAccessToken() {}
verifyScope() {}
// ...
// check more codes in test/src/test-model.service.ts
}
使用量
该模块还提供一些精美的装饰来帮助配置oauth2处理器端点. 下面给出一个覆盖全部装潢阵列的示例控制器
oauth2.controller.ts
import { Controller } from '@nestjs/common';
import {
OAuth2Authorization,
OAuth2Authorize,
OAuth2RenewToken,
OAuth2Token,
} from '@boyuai/nestjs-oauth2-server';
@Controller()
export class OAuth2Controller {
@Post()
@OAuth2Authenticate()
authenticateClient(@OAuth2Token() token: Token) {
return token;
}
@Post()
@OAuth2Authorize()
authorizeClient(
@OAuth2Authorization()
authorization: AuthorizationCode,
) {
return authorization;
}
@Post()
@OAuth2RenewToken()
renewToken(@OAuth2Token() token: Token) {
return token;
}
}
Async 配置
该模块也可同步使用 forRootAsync 方法.
实例如下:
- 采用工厂供应商办法
import { Module } from '@nestjs/common';
import {
OAuth2ServerModule,
IOAuth2ServerModuleOptions,
} from '@boyuai/nestjs-oauth2-server';
@Module({
imports: [
// ... other modules
OAuth2ServerModule.forRootAsync({
useFactory: (factory: IOAuth2ServerOptionsFactory) => ({}),
modelClass: YourModelService,
}),
],
})
export class YourModule {}
- 采用类或现有提供者办法:
oauth2-server-config.service.ts
import {
IOAuth2ServerModuleOptions,
IOAuth2ServerOptionsFactory,
} from '@boyuai/nestjs-oauth2-server';
import { Injectable } from '@nestjs/common';
@Injectable()
export class OAuth2ServerConfigService
implements IOAuth2ServerOptionsFactory {
createOAuth2ServerOptions(): IOAuth2ServerModuleOptions {
return {};
}
}
这个 OAuth2ServerConfigService 应该 执行 IOAuth2ServerOptionsFactory, (中文(简体) ), 必须 声明 createOAuth2ServerOptions 方法和 必须 返回时 IOAuth2ServerModuleOptions 对象.
import { Module } from '@nestjs/common';
import { OAuth2ServerModule } from '@boyuai/nestjs-oauth2-server';
import { OAuth2ServerConfigService } from './oauth2-server-config.service.ts';
@Module({
imports: [
// ... other modules
OAuth2ServerModule.forRootAsync({
useClass: OAuth2ServerConfigService,
modelClass: YourModelService,
}),
],
})
export class YourModule {}
学习
本条可进一步理解OAuth2的概念 这里。也可以去Oauth2服务器包 文档。 。 。 .
捐款
但是,欢迎关于改进的建议,请遵守《公约》 捐款 准则.