在后端,我们使用在端口3000:上运行的nestjs typescript
import { PassportStrategy } from '@nestjs/passport';
import { Strategy, VerifyCallback } from 'passport-google-oauth20';
import { config } from 'dotenv';
import { Injectable } from '@nestjs/common';
config();
@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
constructor() {
super({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_SECRET,
callbackURL: 'http://localhost:3000/auth/redirect',
scope: ['email', 'profile'],
});
}
async validate(accessToken: string, refreshToken: string, profile: any, done: VerifyCallback): Promise<any> {
const { name, emails, photos, id } = profile;
const user = {
googleId: id,
email: emails[0].value,
firstName: name.givenName,
lastName: name.familyName,
picture: photos[0].value,
accessToken,
};
done(null, user);
}
}
在前端,我们运行3001,在我选择谷歌帐户后,它必须重定向到http://localhost:3001/role-选择。
const googleAuth = () => {
window.open(`http://localhost:3000/auth/redirect`, '_self');
if (token) navigate('role-selection');
};
return (
<Container onClick={googleAuth}>
<Image src={googleIcon} />
<Typography>{`${t('GoogleAuthButton.googleAuth')}`}</Typography>
</Container>
);
}
这是谷歌按钮组件。我该如何连接?我也接受葡萄牙语的回答:D,请大家帮帮我。
我可以自己解决这个问题,并希望发布解决方案:这是我的cotroller文件:
@Get('redirect')
@UseGuards(AuthGuard('google'))
googleAuthRedirect(@Req() req, @Res() res) {
this.authService.googleSignUp(req);
res.redirect('http://localhost:3001/role-selection');
}
我希望这能帮助其他人。