我通过两种不同的策略在我的 NestJS 应用程序中实现了 Google 和 Dropbox 身份验证。
问题是我从来没有得到refresh_token和access_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 };
});
});
}
}
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});
}
}
我在访问用户的 Google 日历时遇到了同样的问题。我的问题是我有如下所示的控制器
@Public()
@Get('google')
@UseGuards(AuthGuard('jwt'))
async googleAuth(): Promise<{ url: string }> {
const url = getCalendarOAuthRequestUrl(this.configService);
return { url };
}
@Get('/google/callback')
@UseGuards(GoogleCalendarGuard)
async googleAuthCallback(@Req() req) {
const { accessToken, refreshToken } = req.user;
// logic...
}
经过数小时的研究和浪费精力,我注意到生成 Google OAuth URL 的 getCalendarOAuthRequestUrl() 函数缺少提示和访问类型,添加它们后我开始收到刷新令牌。 您的 Google OAuth 请求 URL 应如下所示
https://accounts.google.com/o/oauth2/auth?access_type=offline&prompt=consent&client_id=<YourClientId>&redirect_uri=<YourRedirectUrl>&response_type=code&scope=profile email <AnyGoogleScopeYouNeed>
在回调端点守卫中,您还将收到刷新令牌。