-
Notifications
You must be signed in to change notification settings - Fork 0
Setting Up Authentication with AWS Cognito
Dominique Hosea edited this page Jul 12, 2024
·
1 revision
- Create a Cognito User Pool: Configure a new user pool in the AWS Cognito console.
- Configure App Client: Set up an app client in Cognito without a client secret.
- Set Up Federated Identity Pool: Link the user pool to an identity pool for AWS services access.
-
Install AWS Amplify:
npm install aws-amplify - Configure Amplify:
// src/aws-exports.js
const awsconfig = {
Auth: {
region: "YOUR_AWS_REGION",
userPoolId: "YOUR_USER_POOL_ID",
userPoolWebClientId: "YOUR_APP_CLIENT_ID",
identityPoolId: "YOUR_IDENTITY_POOL_ID",
}
};
export default awsconfig;
// src/index.js
import Amplify from 'aws-amplify';
import awsconfig from './aws-exports';
import App from './App';
Amplify.configure(awsconfig);Create a context to manage authentication state.
// src/contexts/AuthContext.js
import { createContext, useContext, useState, useEffect } from 'react';
import { Auth } from 'aws-amplify';
const AuthContext = createContext();
export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
useEffect(() => {
Auth.currentAuthenticatedUser()
.then(user => setUser(user))
.catch(() => setUser(null));
}, []);
const signIn = async (username, password) => {
try {
const user = await Auth.signIn(username, password);
setUser(user);
return user;
} catch (error) {
console.error("Error signing in", error);
throw error;
}
};
const signOut = async () => {
try {
await Auth.signOut();
setUser(null);
} catch (error) {
console.error("Error signing out", error);
throw error;
}
};
return (
<AuthContext.Provider value={{ user, signIn, signOut }}>
{children}
</AuthContext.Provider>
);
};
export const useAuth = () => useContext(AuthContext);© 2024 Mun-e. All rights reserved.