AWS Cognito provides authentication, authorization, and user management for your webapps. In this article I will show Angular snippets to perform authentication with AWS Cognito credentials.
First, I'll show the CognitoService
class with just signIn
functionality. I've removed other operations like register, confirm registration, etc. from the snippet for simplicity.
const poolData = {
UserPoolId: 'us-east-1_XXXXXXXXX', // Your user pool id here
ClientId: 'XXXXXXXXXXXXXXXXXXXXXXXXXX' // Your client id here
};
const userPool = new CognitoUserPool(poolData);
@Injectable({
providedIn: 'root'
})
export class CognitoService {
constructor() { }
signIn(username, password) {
const authenticationData = {
Username: username,
Password: password
};
const authenticationDetails = new AuthenticationDetails(authenticationData);
const userData = {
Username: username,
Pool: userPool
};
const cognitoUser = new CognitoUser(userData);
return Observable.create(observer => {
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: (result) => {
observer.next(result);
observer.complete();
},
onFailure: (err) => {
console.log(err);
observer.error(err);
}
});
});
}
}
And in the LoginComponent
class
export class LoginComponent implements OnInit {
userCredentialsModel: UserCredentialsModel = {};
loading = false;
errorMessage = '';
constructor(
private router: Router,
private cognitoService: CognitoService
) { }
login() {
this.errorMessage = '';
this.loading = true;
this.cognitoService.signIn(
this.userCredentialsModel.userName,
this.userCredentialsModel.password).subscribe(
(data) => {
this.loading = false;
this.router.navigate(['/securedpage']);
},
(error) => {
this.loading = false;
this.errorMessage = error.message;
}
);
}
}
Hope this helps!