@inube/iauth-react
v2.1.0
Published
A react authentication library for inube portals
Readme
Inube IAuth
This is a React and Vite component library for managing authentication for @Inube applications using the iAuth service.
Features
This library provides authentication integration with the Inube iAuth service. It offers the following features:
- Login with redirect - Redirect to iAuth authentication service
- Logout - Clear session and optionally redirect
- Get access token - Retrieve current access token
- Get user information - Extract user data from JWT tokens via iAuth service
- Check if user is authenticated - Authentication state management
- Check if user is loading - Loading state during auth processes
- Automatic token handling - Process authentication codes from iAuth callbacks
- Save user information in localStorage - Persistent sessions across browser restarts
- Error handling - Comprehensive error management for auth flows
Currently, this library is designed specifically for Inube's iAuth authentication service.
Installation
Run the following command using npm:
npm install --save @inube/iauth-reactConfiguration
IAuthProvider Props:
- clientId:
string- ID of the client registered in iAuth - clientSecret:
string- Secret of the client registered in iAuth - originatorId:
string- Originator identifier for the authentication request - callbackUrl:
string- Callback URL where iAuth will redirect after authentication - iAuthUrl:
string- Base URL of the iAuth authentication service - serviceUrl:
string- Persistence authentication login URL address.
Note: Save these values in environment variables for security.
Usage
Basic Setup
import React, { useEffect } from "react";
import ReactDOM from "react-dom/client";
import { IAuthProvider, useIAuth } from "@inube/iauth";
const CLIENT_ID = import.meta.env.VITE_AUTH_CLIENT_ID;
const CLIENT_SECRET = import.meta.env.VITE_AUTH_CLIENT_SECRET;
const ORIGINATOR_ID = import.meta.env.VITE_AUTH_ORIGINATOR_ID;
const CALLBACK_URL = import.meta.env.VITE_AUTH_CALLBACK_URL;
const IAUTH_URL = import.meta.env.VITE_AUTH_URL;
ReactDOM.createRoot(document.getElementById("root")!).render(
<IAuthProvider
clientId={CLIENT_ID}
clientSecret={CLIENT_SECRET}
originatorId={ORIGINATOR_ID}
callbackUrl={CALLBACK_URL}
iAuthUrl={IAUTH_URL}
>
<App />
</IAuthProvider>
);
// App component
function App() {
const { user, isAuthenticated, isLoading, loginWithRedirect } = useIAuth();
useEffect(() => {
if (!isLoading && !isAuthenticated) {
loginWithRedirect();
}
}, [isLoading, isAuthenticated, loginWithRedirect]);
if (isLoading) {
return <div>Loading...</div>;
}
if (!isAuthenticated) {
return null;
}
return (
<div>
<h1>Welcome, {user?.username}!</h1>
<p>Successfully logged in: {JSON.stringify(user)}</p>
<button onClick={() => logout()}>Logout</button>
</div>
);
}API Reference
useIAuth Hook
The useIAuth hook provides access to the authentication context:
const {
user, // Current user information
setUser, // Function to set user manually
isAuthenticated, // Boolean indicating if user is authenticated
isLoading, // Boolean indicating if auth is loading
error, // Current error state
clearError, // Function to clear errors
loginWithRedirect, // Function to initiate login
logout, // Function to logout
getAccessTokenSilently, // Function to get access token
} = useIAuth();Types
IUser
interface IUser {
id: string;
identificationType: string;
username: string;
nickname: string;
company: string;
urlImgPerfil: string;
}RedirectLoginOptions
interface RedirectLoginOptions {
authorizationParams?: Record<string, any>;
appState?: Record<string, any>;
[key: string]: any;
}LogoutOptions
interface LogoutOptions {
logoutParams?: {
returnTo?: string;
};
}Methods
loginWithRedirect(options?)
Redirects the user to the iAuth authentication service.
loginWithRedirect({
authorizationParams: {
custom_param: "value",
},
appState: {
returnTo: "/dashboard",
},
});logout(options?)
Logs out the user and clears stored authentication data.
logout({
logoutParams: {
returnTo: "/login",
},
});getAccessTokenSilently()
Returns a promise that resolves to the current access token.
try {
const token = await getAccessTokenSilently();
// Use token for API calls
} catch (error) {
console.error("No access token available:", error);
}Environment Variables
Create a .env file with the following variables:
# Required iAuth Configuration
VITE_AUTH_CLIENT_ID=your_client_id
VITE_AUTH_CLIENT_SECRET=your_client_secret
VITE_AUTH_ORIGINATOR_ID=your_originator_id
VITE_AUTH_CALLBACK_URL=http://localhost:3000/callback
VITE_AUTH_URL=https://your-iauth-service-url
VITE_AUTH_SERVICE=https://your-iauth-service-urlAuthentication Flow
- Initial Load: The library checks for existing authentication data in localStorage
- Login Redirect: If not authenticated, user is redirected to iAuth service
- Callback Handling: iAuth redirects back with an access code (
acparameter) - Token Exchange: The access code is exchanged for user data via the iAuth API
- User Data: JWT token is decoded to extract user information
- Persistent Storage: Authentication data is stored in localStorage for future sessions
Error Handling
The library provides comprehensive error handling:
function App() {
const { error, clearError, isAuthenticated } = useIAuth();
if (error) {
return (
<div>
<h2>Authentication Error</h2>
<p>{error.message}</p>
<button onClick={clearError}>Try Again</button>
</div>
);
}
}URL Parameters
The library automatically handles these URL parameters:
ac- Access code returned by iAuth after successful authenticationerror- Error code if authentication failederror_description- Detailed error description
These parameters are automatically cleaned from the URL after processing.
Local Storage
The library stores the following data in localStorage:
auth_token- Access token for API callsauth_user- Serialized user information
Data is automatically cleared on logout or authentication errors.
API Integration
The library integrates with the iAuth persistence service:
- Service URL:
https://four.external.iauth.persistence.process.inube.dev/iauth-persistence-process-service/api - Endpoint:
/user-accounts - Authentication: Basic auth using client credentials
- Timeout: 5 seconds for API calls
Security Features
- Secure Storage: Authentication data stored in localStorage
- Automatic Cleanup: Tokens are cleared on logout or error
- Error Recovery: Invalid stored data is automatically cleaned
- URL Cleanup: Authentication parameters are removed from URL after processing
Development
The components are developed using:
- TypeScript for type safety
- React Hooks for state management
- JWT handling for token processing
- iAuth API integration for user data retrieval
Code is committed using Conventional Commits and releases are managed using auto by Intuit.
Requirements
- React >= 16.8.0
- TypeScript (for TypeScript projects)
- Valid iAuth service credentials
Browser Support
- Chrome (latest)
- Firefox (latest)
- Safari (latest)
- Edge (latest)
Issues
If you encounter any issues while using the library, please report them as issues here.
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Support
For questions and support, please visit our documentation or create an issue in the repository.
