Loading repository data…
Loading repository data…
Angular-2022-2023 / repository
Implementation of Amazon Cognito Authentication in Angular application using AWS Amplify for Authentication and Session Management
A transparent discovery signal based on current public GitHub metadata.
This score does not audit code, security, maintainers, documentation quality, or suitability. Verify the repository and its current documentation before adoption.
Créez un pool d'utilisateurs Amazon Cognito.
Pour installer Angular CLI, ouvrez une fenêtre de terminal et exécutez la commande suivante :
npm install -g @angular/cli
Exécutez la commande ci-dessous pour créer un nouveau projet Angular.
ng new hello-world --no-standalone
Installez la bibliothèque @aws-amplify/ui-angular ainsi que aws-amplify si ce n'est pas déjà fait :
npm install aws-amplify @aws-amplify/ui-angular
Utilisez le code suivant pour configurer l'application AWS Amplify avec des ressources AWS existantes.
Amplify.configure({
Auth: {
Cognito: {
userPoolId: 'ap-south-1_xxxxx',
userPoolClientId: '71h7gnxxxxxxxxx'
}
}
});
Pour le CSS, utilisez le code ci-dessous :
@import '@aws-amplify/ui/dist/styles.css';
Ajoutez le composant d'authentification dans le fichier HTML.
<amplify-authenticator>
<ng-template
amplifySlot="authenticated"
let-user="user"
let-signOut="signOut"
>
<h1>Bienvenue {{ user.username }} !</h1>
<button (click)="signOut()">Déconnexion</button>
</ng-template>
</amplify-authenticator>
Mettez à jour le composant d'authentification avec les champs d'inscription.
<amplify-authenticator [loginMechanisms]="['email']" [signUpAttributes]="['name']">
Référence - Sign Up Attributes
Pour mettre à jour l'ordre des champs, utilisez l'attribut formFields.
<amplify-authenticator [loginMechanisms]="['email']" [formFields]="formFields" [signUpAttributes]="['name']">
formFields = {
signUp: {
name: {
order: 1
},
email: {
order: 2
},
password: {
order: 5
},
confirm_password: {
order: 6
}
},
};
Créez le fichier src/polyfills.ts et ajoutez ce qui suit :
Cette étape est nécessaire pour assurer la compatibilité avec certaines bibliothèques JavaScript qui s'attendent à un environnement de type Node.js en ajoutant des objets globaux comme global et process. Cela permet d'éviter des erreurs lors de l'exécution de l'application Angular dans un navigateur.
(window as any).global = window;
(window as any).process = {
env: { DEBUG: undefined },
};
Ensuite, ouvrez votre fichier angular.json et ajoutez src/polyfills.ts au tableau polyfills dans votre angular.json.
"polyfills": [
"zone.js",
"src/polyfills.ts"
],
Enfin, assurez-vous d'ajouter src/polyfills aux fichiers dans votre tsconfig.
{
"files": [
"src/main.ts",
"src/polyfills.ts"
],
}
Pour obtenir le JWT Token et les détails de l'utilisateur, créez une classe AuthService.ts.
import { Injectable } from '@angular/core';
import { AuthUser, getCurrentUser, signOut, fetchAuthSession, AuthTokens } from 'aws-amplify/auth';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor() { }
async getCurrentUser(): Promise<AuthUser> {
return await getCurrentUser();
}
async getCurrentSession(): Promise<AuthTokens | undefined> {
return (await fetchAuthSession()).tokens;
}
async getCurrentUserFullName(): Promise<string | undefined> {
let cognitoToken = await (await fetchAuthSession()).tokens;
return cognitoToken?.idToken?.payload['name']?.toString();
}
signOut() {
signOut();
}
}