A react authentication library for inube portals
npm install @inube/iauth-reactbash
npm install --save @inube/iauth-react
`
Configuration
$3
- 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
$3
`tsx
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(
clientId={CLIENT_ID}
clientSecret={CLIENT_SECRET}
originatorId={ORIGINATOR_ID}
callbackUrl={CALLBACK_URL}
iAuthUrl={IAUTH_URL}
>
);
// App component
function App() {
const { user, isAuthenticated, isLoading, loginWithRedirect } = useIAuth();
useEffect(() => {
if (!isLoading && !isAuthenticated) {
loginWithRedirect();
}
}, [isLoading, isAuthenticated, loginWithRedirect]);
if (isLoading) {
return Loading...;
}
if (!isAuthenticated) {
return null;
}
return (
Welcome, {user?.username}!
Successfully logged in: {JSON.stringify(user)}
);
}
`
API Reference
$3
The useIAuth hook provides access to the authentication context:
`tsx
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();
`
$3
#### IUser
`tsx
interface IUser {
id: string;
identificationType: string;
username: string;
nickname: string;
company: string;
urlImgPerfil: string;
}
`
#### RedirectLoginOptions
`tsx
interface RedirectLoginOptions {
authorizationParams?: Record;
appState?: Record;
[key: string]: any;
}
`
#### LogoutOptions
`tsx
interface LogoutOptions {
logoutParams?: {
returnTo?: string;
};
}
`
$3
#### loginWithRedirect(options?)
Redirects the user to the iAuth authentication service.
`tsx
loginWithRedirect({
authorizationParams: {
custom_param: "value",
},
appState: {
returnTo: "/dashboard",
},
});
`
#### logout(options?)
Logs out the user and clears stored authentication data.
`tsx
logout({
logoutParams: {
returnTo: "/login",
},
});
`
#### getAccessTokenSilently()
Returns a promise that resolves to the current access token.
`tsx
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:
`env
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-url
`
Authentication Flow
1. Initial Load: The library checks for existing authentication data in localStorage
2. Login Redirect: If not authenticated, user is redirected to iAuth service
3. Callback Handling: iAuth redirects back with an access code (ac parameter)
4. Token Exchange: The access code is exchanged for user data via the iAuth API
5. User Data: JWT token is decoded to extract user information
6. Persistent Storage: Authentication data is stored in localStorage for future sessions
Error Handling
The library provides comprehensive error handling:
`tsx
function App() {
const { error, clearError, isAuthenticated } = useIAuth();
if (error) {
return (
Authentication Error
{error.message}
);
}
}
`
URL Parameters
The library automatically handles these URL parameters:
- ac - Access code returned by iAuth after successful authentication
- error - Error code if authentication failed
- error_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 calls
- auth_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
1. Fork the repository
2. Create your feature branch (git checkout -b feature/amazing-feature)
3. Commit your changes (git commit -m 'Add some amazing feature')
4. Push to the branch (git push origin feature/amazing-feature`)