我正在寻找一个如何使用NestJS实现Auth0 Authorization Code Grant流程的示例。
答案 0 :(得分:1)
为了在处理exchange of the Authorization Code for an Access Token的后端创建POST
端点/authenticate
,我们需要先定义端点所需的dto。
从客户端我们希望对象具有authorization_code
和origin
字段。
<强>授权-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_DOMAIN
和YOUR_CLIENT_ID
。