我正在使用AWS Cognito通过Google联合身份验证我的网站用户。一切似乎都正常工作,返回了正确的令牌(据我所知),并且用户似乎已通过身份验证。但是,我不知道如何将Google用户自动添加到我的Cognito用户池中,并且我还没有找到任何文档可以帮助我。有什么想法吗?
这是我的Angular代码:
import { Component, OnInit } from '@angular/core';
import { environment } from "src/environments/environment";
import { Cookie } from 'ng2-cookies/ng2-cookies';
import Auth from '@aws-amplify/auth';
declare const gapi: any;
declare const AWS: any;
const config = Auth.configure({
identityPoolId: environment.AWS_IDENTITY_POOL_ID,
region: environment.AWS_REGION,
userPoolId: environment.AWS_USER_POOL_ID,
userPoolWebClientId: environment.CLIENT_ID
});
@Component({
selector: 'authentication',
templateUrl: './authentication.component.html',
styleUrls: ['./authentication.component.sass']
})
export class AuthenticationComponent implements OnInit {
public auth2: any;
constructor() { }
ngOnInit() {
this.googleInit();
}
// called immediately, preps for the click of the google button
googleInit() {
// google's function to prep user
gapi.load('auth2', () => {
this.auth2 = gapi.auth2.init({
access_type: "offline",
client_id: environment.GOOGLE_ID,
client_secret: environment.CLIENT_SECRET,
cookiepolicy: 'single_host_origin',
scope: 'profile email'
});
// calls this on sign in
this.attachSignin(document.getElementById('googleBtn'));
});
}
// once a user is in the pop up login window
attachSignin(element) {
this.auth2.attachClickHandler(element, {},
// this part is called if they successfully sign in
(googleUser) => {
// stores the user's profile
let profile = googleUser.getBasicProfile();
this.getCreds(googleUser.getAuthResponse(), profile.getEmail(), profile.getName())
// this is called if the sign in does not work or if they close the window or anything of that sort
}, (error) => {
console.log(JSON.stringify(error, undefined, 2));
});
}
getCreds(authResult: any, email: string, name: string) {
Auth.federatedSignIn('google', {
token: authResult.id_token,
expires_at: authResult.expires_at
}, {email, name}
).then(response => {
console.log(response);
return Auth.currentAuthenticatedUser();
}).catch(e => {
console.log(e)
});
this.queryAWS(authResult.id_token);
}
queryAWS(id_token: any) {
AWS.config.region = environment.AWS_REGION;
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: environment.AWS_IDENTITY_POOL_ID,
Logins: { "accounts.google.com": id_token }
});
AWS.config.credentials.get(err => {
if (!err) {
Cookie.set('awsAuthenticated', 'true', 7);
sessionStorage.setItem('expireTime', AWS.config.credentials['expireTime']);
}
else {
console.log(err);
}
});
}
}