使用NestJS授权Auth0授权代码

时间:2018-05-15 16:01:42

标签: javascript node.js typescript auth0 nestjs

我正在寻找一个如何使用NestJS实现Auth0 Authorization Code Grant流程的示例。

1 个答案:

答案 0 :(得分:1)

为了在处理exchange of the Authorization Code for an Access Token的后端创建POST端点/authenticate,我们需要先定义端点所需的dto

从客户端我们希望对象具有authorization_codeorigin字段。

<强>授权-request.dto.ts

export class AuthorizationRequestDto {
  readonly authorization_code: string;
  readonly origin: string;
}

现在我们可以创建controller来处理发送给POST的{​​{1}}次请求:

/authenticate

当然,在上面的代码中,我们需要替换import { Body, Controller, HttpService, Post } from '@nestjs/common'; import { AxiosResponse } from '@nestjs/common/http/interfaces/axios.interfaces'; import { Observable } from 'rxjs/internal/Observable'; import { map } from 'rxjs/operators'; import { AuthorizationRequestDto } from './authorization-request.dto'; @Controller('authenticate') export class AuthController { constructor(private readonly httpService: HttpService) {} @Post() authenticate(@Body() authorizationRequestDto: AuthorizationRequestDto): Observable<AxiosResponse<any>> { return this.httpService.post('https://YOUR_AUTH0_DOMAIN/oauth/token', { grant_type: 'authorization_code', client_id: 'YOUR_CLIENT_ID', client_secret: 'YOUR_CLIENT_SECRET', code: authorizationRequestDto.authorization_code, redirect_uri: authorizationRequestDto.origin, }).pipe( map(response => response.data), ); } } YOUR_AUTH0_DOMAINYOUR_CLIENT_ID