Quick Start
System for authentication for your web application.
To get started with using the react-authentication
package for your website, follow these steps:
Step 1: Installation
First, install the react-authentication
package using npm or yarn:
npm install @resourge/react-authentication
# or
yarn add @resourge/react-authentication
Step 2: Setting up Authentication
Create an Authentication
component in your project. This component will handle authentication-related functionality:
import React, { useEffect } from 'react';
import { setupAuthentication, AuthenticationSystem, SessionService } from '@resourge/react-authentication';
import { LoadingFallback } from '@resourge/react-fetch';
import { Navigate, useNavigate } from '@resourge/react-router';
import { Hub } from 'aws-amplify';
import AuthenticationService from './shared/services/AuthenticationService';
import HttpService from './shared/services/HttpService';
import RoutePaths from './shared/routes/Routes';
// Ensure to import any required types/interfaces
const authentication = setupAuthentication(
() => AuthenticationService.getAuthentication()
);
const Authentication: React.FC<Props> = ({ children }: Props) => {
const navigate = useNavigate();
const onLogout = () => {
AuthenticationService.logout();
};
return (
<AuthenticationSystem
authentication={authentication}
loadingComponent={<LoadingFallback />}
redirectOnError={true}
errorComponent={isProduction ? (() => <Navigate to={RoutePaths.ERROR[502].get()} />) : undefined}
onError={isProduction ? onLogout : undefined}
onLogout={onLogout}
onLogin={async (username, password) => {
try {
return await AuthenticationService.login(username, password);
}
catch ( e ) {
// Handle login errors, such as redirecting to a specific URL
return await Promise.reject(e);
}
}}
onRefreshToken={() => AuthenticationService.refreshToken()}
onToken={(token, user) => {
// Set token and user information for HTTP requests
HttpService.setToken((config) => {
if ( token ) {
config.headers.Authorization = config.headers.Authorization ?? `Bearer ${token}`;
config.headers.idToken = user.idToken;
}
return config;
});
}}
>
{ children }
</AuthenticationSystem>
);
};
export default Authentication;
Step 3: Usage
Now you can use the useAuthentication
and usePermissions
hooks in your components to access authentication and permissions contexts:
// Custom hook for authentication
import { useAuthenticationContext } from '@resourge/react-authentication';
import { User } from './User';
export const useAuthentication = () => {
return useAuthenticationContext<User>();
};
// Custom hook for permissions
import { usePermissionsContext } from '@resourge/react-authentication';
import { Permissions } from './Permissions';
export const usePermissions = () => {
return usePermissionsContext<Permissions>();
};
Certainly! You can add another section to your documentation explaining how to implement an error boundary around your authentication and routing components in the App.tsx
file. Here’s how you can structure it:
Step 4: Implementing Error Boundary
You can enhance error handling in your application by wrapping the authentication and routing components with an ErrorBoundary
provided by react-authentication
. This will catch errors that occur within these components and handle them gracefully. Here’s how you can implement it in your App.tsx
file:
import React from 'react';
import { ErrorBoundary } from '@resourge/react-authentication';
import { Router } from './Router'; // Assuming this is your Router component
import Authentication from './Authentication'; // Assuming this is your Authentication component
import RoutePaths from './shared/routes/Routes';
const App: React.FC = () => {
return (
<ErrorBoundary onError={() => window.history.pushState(null, '', RoutePaths.ERROR[502].get())}>
<Authentication>
<Router />
</Authentication>
</ErrorBoundary>
);
};
export default App;
By wrapping your Authentication
component with an ErrorBoundary
, any errors that occur within it or its child components will be caught, allowing you to handle them appropriately. In this example, we’ve provided a callback function to navigate to a specific error page (RoutePaths.ERROR[502].get()
) when an error occurs. You can customize this behavior based on your application’s requirements.
With this implementation, your application will have improved error handling, ensuring a smoother user experience even when unexpected errors occur during authentication or routing.
With these steps, you have set up authentication for your Astro website using the react-authentication
package. You can now handle user authentication and permissions in your application.
Step 5: Log in
To perform a login operation in your LoginPage.tsx
file, you can utilize the useAuthentication
hook provided by react-authentication
. This hook allows you to access authentication-related functionality within your components. Here’s how you can integrate it into your LoginPage.tsx
:
import React, { useState } from 'react';
import { useAuthentication } from '@resourge/react-authentication';
const LoginPage: React.FC = () => {
const { login } = useAuthentication();
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const handleLogin = async () => {
try {
await login(username, password);
// Redirect or perform any actions upon successful login
} catch (error) {
setError('Failed to login. Please check your credentials.');
}
};
return (
<div>
<h2>Login</h2>
<div>
<input type="text" placeholder="Username" value={username} onChange={(e) => setUsername(e.target.value)} />
</div>
<div>
<input type="password" placeholder="Password" value={password} onChange={(e) => setPassword(e.target.value)} />
</div>
{error && <div>{error}</div>}
<button onClick={handleLogin}>Login</button>
</div>
);
};
export default LoginPage;
Explanation:
- We import the
useAuthentication
hook from@resourge/react-authentication
. - Inside the component, we initialize the hook and extract the
login
function from it. - We manage the state of
username
,password
, anderror
using theuseState
hook. - The
handleLogin
function is responsible for calling thelogin
function with the providedusername
andpassword
. - Upon successful login, you can redirect the user or perform any desired actions.
- If an error occurs during login, we catch it and display an error message.
By following these steps, you can enable users to log in to your application using the useAuthentication
hook provided by react-authentication
.