在NestJs中实现OAuth1

时间:2019-07-16 06:25:58

标签: nestjs

我正在尝试为Atlassian堆栈(竹子)设置带有PassportJs的NestJs 不幸的是,文档仅说明了如何使用本地身份验证。

我阅读了文档,Nestjs的PassportJs应该提供我使用的策略,但是我在NestJS中遇到“ OAuth身份验证需要会话支持”错误。

所以我尝试在auth.module.ts中进行配置。

import { HttpModule, Module } from '@nestjs/common';
import { AuthController } from '../Controller/auth.controller';
import { AppService } from '../../app.service';
import { ConfigModule } from '../../config/config.module';
import { OAuth1 } from '../strategy/o-auth1.service';
import { PassportModule } from '@nestjs/passport';

@Module({
  imports: [HttpModule, ConfigModule, PassportModule.register({ session: true })],
  controllers: [AuthController],
  providers: [AppService, OAuth1],
  exports: [PassportModule.register({ session: true })],
})

export class AuthModule {
}

这将是模块

import { ConfigService } from '../../config/config.service';
import { Injectable, Req, Res } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-atlassian-oauth';
import { ExpressSessionMiddleware } from '@nest-middlewares/express-session';
import { Request, Response } from 'express';

@Injectable()
export class OAuth1 extends PassportStrategy(Strategy, 'oauth1') {
  constructor(private readonly envConfig: ConfigService) {
    super(
      {
        applicationURL: 'http://localhost:8085/',
        consumerKey: consumerkey,
        consumerSecret: consumerSecret,
        callbackURL: envConfig.thisCallbackURL,
      },
      (token, tokenSecret, profile, cb) => {
        User.findOrCreate({ exampleId: profile.id }, (err, user) => {
          return cb(err, user);
        });
      },
    );
  }
}

这是已实施的策略

@Get('')
  @UseGuards(AuthGuard('oauth1'))
  async auth(@Req() req: Request, @Res() res: Response): Promise<string> {
    console.log(this);
    try {
      console.log('');
    } catch (e) {
      console.log(e);
    }
    res.send('hallo');
    return 'test';
  }

这是控制器

我尝试玩耍,但找不到任何解决方法

1 个答案:

答案 0 :(得分:1)

将此添加到您的main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import session = require('express-session');

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.use(session({ secret: 'you secret', saveUninitialized: true, resave: true }));
  await app.listen(3010);
}

bootstrap();