我正在尝试在我的角度应用程序中实现谷歌登录功能。我这里用了两个包
@abacritt/angularx-social-login
和angular-oauth2-oidc
。
我创建了一个名为
google-authentication.service.ts
的自定义提供程序,与此存储库中的 Link 相同。使用这种方法,成功登录后,对话框不会关闭,而且我也无法获取登录用户的详细信息。
问题:请建议一种在成功登录后关闭对话框并获取登录用户凭据的方法
google-authentication.service.ts:
@Injectable()
export class GoogleAuthenticationService implements LoginProvider {
constructor(private readonly _oAuthService: OAuthService) {
this.createConfiguration();
}
private readonly _tokenReceived$ = this._oAuthService.events.pipe(
filter((e) => e.type === 'token_received'),
map(() => true as const)
);
private createConfiguration(): void {
let redirectUri = window.location.origin + window.location.pathname;
if (redirectUri.endsWith('/')) {
redirectUri = redirectUri.substring(0, redirectUri.length - 1);
}
this._oAuthService.configure({
issuer: 'https://accounts.google.com',
strictDiscoveryDocumentValidation: false,
redirectUri,
silentRefreshRedirectUri: redirectUri,
useSilentRefresh: true,
clientId: environment.googleClientId,
scope: 'openid profile email'
});
}
async initialize(autoLogin?: boolean): Promise<void> {
await this._oAuthService.loadDiscoveryDocument();
if (autoLogin) {
await this._oAuthService.tryLoginImplicitFlow();
}
}
async signIn(): Promise<SocialUser> {
const tokenReceivedPromise = firstValueFrom(this._tokenReceived$);
await this._oAuthService.initImplicitFlowInPopup();
await tokenReceivedPromise;
return this.createUser(this._oAuthService.getIdToken());
}
async getLoginStatus(): Promise<SocialUser> {
if (this._oAuthService.hasValidIdToken()) {
return this.createUser(this._oAuthService.getIdToken());
} else {
throw `No user is currently logged in`;
}
}
async signOut(revoke?: boolean): Promise<void> {
if (revoke) {
this._oAuthService.revokeTokenAndLogout(true, true);
} else {
this._oAuthService.logOut(true);
}
}
private createUser(idToken: string): SocialUser {
const user = new SocialUser();
const payload = JSON.parse(window.atob(idToken.split('.')[1]));
user.idToken = idToken;
user.id = payload.sub;
user.name = payload.name;
user.email = payload.email;
user.photoUrl = payload.picture;
user.firstName = payload['given_name'];
user.lastName = payload['family_name'];
return user;
}
}
登录组件.ts
ngOnInit(): void {
this._googleAuthService.initialize();
}
signUpWithGoogle(event: Event): void {
this._googleAuthService
.signIn()
.then((user) => {
//not showing anything in console
console.log(user);
})
.catch((error) => {
console.log(error);
});
}
这样对我来说很有效。 根据Google的新文档(https://developers.google.com/identity/gsi/web/guides/overview),您应该遵循以下步骤:
在google云控制台平台创建google应用程序并生成客户端id。
加载客户端库。在 Angular 项目的 index.html 文件的
<script src="https://accounts.google.com/gsi/client
标签之间添加此脚本“<head></head>
”async defer>”。
将此代码添加到您想要“使用 Google 按钮登录”的组件中的 ngOnInit() 函数上。
ngOnInit() { // @ts-ignore google.accounts.id.initialize({ client_id: "YOUR GOOGLE CLIENT ID", callback: this.handleCredentialResponse.bind(this), auto_select: false, cancel_on_tap_outside: true, }); // @ts-ignore google.accounts.id.renderButton( // @ts-ignore document.getElementById("google-button"), { theme: "outline", size: "large", width: "100%" } ); // @ts-ignore google.accounts.id.prompt((notification: PromptMomentNotification) => {}); }
async handleCredentialResponse(response: any) { // Here will be your response from Google. console.log(response); }
<div class="" id="google-button"></div>.
如果您有任何问题,请告诉我。
我获得了“使用谷歌登录”选项,并且还获得了gmail登录,但它没有重定向到我想要的页面