NestJS和PassportJS没有刷新令牌

时间:2019-05-19 16:35:03

标签: oauth passport.js google-oauth dropbox-api nestjs

我通过两种不同的策略在NestJS应用中实现了Google和Dropbox身份验证。

问题在于,我从没有随同access_token一起获得refresh_token。我已经尝试从Google / Dropbox帐户中已授予的应用程序中删除该应用程序,但是没有成功。

import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-google-oauth2';
import { AuthService } from './auth.service';
import { OauthUser } from './oauth-user.entity';
import { UserService } from '../user/user.service';
import { ConfigService } from '../config/config.service';
import { CloudProvider } from '../shared/enums/cloud-service.enum';

@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {

  constructor(private readonly authService: AuthService,
              private readonly userService: UserService,
              private readonly configService: ConfigService) {
    super({
      clientID: configService.get('OAUTH_GOOGLE_ID'),
      clientSecret: configService.get('OAUTH_GOOGLE_SECRET'),
      callbackURL: configService.get('OAUTH_GOOGLE_CALLBACK'),
      passReqToCallback: true,
      scope: ['email', 'profile', 'https://www.googleapis.com/auth/drive.file'],
      accessType: 'offline',
      prompt: 'consent',
      session: false,
    });
  }

  async validate(request: any, accessToken: string, refreshToken: string, oauthUser: OauthUser) {
    console.log('accessToken', accessToken) // <- this one is good
    console.log('refreshtoken', refreshToken) // <- always undefined
    oauthUser.provider = CloudProvider.GOOGLE;
    return this.userService.getOrCreate(oauthUser, accessToken).then(() => {
      return this.authService.getJwtForUser(oauthUser).then(jwt => {
        return { jwt };
      });
    });
  }

}

1 个答案:

答案 0 :(得分:1)

import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy, VerifyCallback } from 'passport-google-oauth20';

import { IUserProfile } from './interfaces/user.interface';

@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      clientID: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
      callbackURL: process.env.GOOGLE_CB_URL,
      scope: ['email', 'profile'],
    });
  }

  authorizationParams(): { [key: string]: string; } {
    return ({
      access_type: 'offline'
    });
  };

  async validate(
    accessToken: string,
    refreshToken: string,
    profile: IUserProfile,
    done: VerifyCallback,
  ): Promise<void> {
    const { emails } = profile;
    console.log(accessToken, refreshToken);
    done(null, {email: emails[0].value, accessToken});
  }
}