hfn-oneauth
v0.2.1
Published
HFN OneAuth web component
Downloads
515
Readme
HFN OneAuth web component
The oneAuth web component is designed to manage authentication for your application. This component can be used to trigger authentication either automatically when the page loads or on-demand based on user interactions.
Usage
In order to handle authentication consistently across all pages of your application, you need to include the web component in a shared part of your app, such as app.jsx
or your layout component. This ensures the authentication component is available globally.
<hfn-oneauth ref={elementRef} config='{"authUrl":"https://xxx.com","realm":"xxx","client_id":"xxx"}' showCancel="true" authType="on-demand" subPath="yoga" />
Attributes
config
(required):
The configuration for the authentication process, including the authUrl, realm, and client_id.
showCancel
(optional):
This attribute enables a cancel button in the error block. It requires the "LandingPage" path to be stored in localStorage. When the cancel button is clicked, the user is redirected back to the landing page.
subPath
(optional): This attribute can be used to provide sub-path of the redirect URL.
authType
(optional):
- Controls when the authentication process is triggered.
- "on-demand": The authentication is triggered only when explicitly called using the method
document.querySelector("hfn-oneauth").triggerAuth()
. This is useful for scenarios where authentication should only occur after a specific user action, like clicking a button. - If authType is not set, the authentication process starts automatically as soon as the page loads.
Handling Authentication
By default, the redirect URI is set to /oneauth/authorization
. After successful authentication through HFN OneAuth, the user is redirected to the /oneauth/authorization
route. This route must be created in your application to handle the authorization response, process the received token, and then redirect the user back to the landing page stored in localStorage.
Handling Logout
To handle the logout event emitted by the component in your app.jsx
or layout.jsx
, you need to set up an event listener that listens for a custom event, such as userLoggedOut
. When the event is triggered, and the event.detail.loggedOut
is true
, you can handle the application logout logic.
<!--
const handleUserLoggedOut = async (event) => {
if (event?.detail?.loggedOut) await logout();
};
useEffect(() => {
elementRef.current = document.querySelector("hfn-oneauth");
// Add the event listener when the element is present
if (elementRef.current) {
elementRef.current.addEventListener("userLoggedOut", handleUserLoggedOut);
}
// Cleanup event listener on unmount or when the path changes
return () => {
if (elementRef.current) {
elementRef.current.removeEventListener(
"userLoggedOut",
handleUserLoggedOut
);
}
};
}, [elementRef]);
-->
Simple HTML Implementation
<!---
<html>
<head>
<script type="module" src="./dist/main.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
<script type="text/javascript">
window.addEventListener('load', (res) => {
const authComp = document.querySelector('hfn-oneauth');
// After successful login, We will get Auth token from the below callback method. Using this token we can fetch SRCM profile information.
authComp.loginCallback = function(res){
if(res?.data?.access_token){
fetch(`https://xxx/me`, {
method:"GET",
headers: {
Accept: "application/json",
Authorization: `Bearer ${res?.data?.access_token}`,
"x-client-id":"xxx",
}
})
.then((r) => {
if (r?.data?.results.length > 0) {
// this closes the oneauth component after successful login
authComp.handleProfileAuthentication(true);
}
})
.catch((e) => {
//In the event of an error, an error block can be displayed, offering options to retry login or cancel, utilizing the handleProfileAuthentication function.
authComp.handleProfileAuthentication(false);
});
}
};
});
</script>
</head>
<body>
<div>
<hfn-oneauth config='{"authUrl":"https://xxx.com","realm":"xxx","client_id":"xxx"}' showCancel="true"/></hfn-oneauth>
</div>
</body>
</html>
-->
React & Gatsby Implementation
npm i hfn-oneauth
In React or Gatsby App:
App.jsx or layout.jsx
<!--
const hfnAuth = useRef();
React.useEffect(() => {
import("hfn-oneauth/main");
});
return (
<hfn-oneauth config='{"authUrl":"https://xxx.com","realm":"xxx","client_id":"xxx"}' showCancel="true" authType="on-demand" /></hfn-oneauth>
);
-->
Handle authentication in "/oneauth/authorization" page
Create a /oneauth/authorization
route in your application to manage post-login processes, handle the authorization logic, and redirect the user appropriately after authentication.
<!--
useEffect(() => {
// After successful login, We will get Auth token from the below callback method. Using this token we can fetch SRCM profile information.
const element = document.querySelector("hfn-oneauth");
element.loginCallback = (res) => {
fetch(`{baseURL}/xxx/me/`, {
headers: {
Accept: "application/json",
Authorization: `Bearer res?.access_token`,
}
})
.then((r) => {
if (r?.data?.results.length > 0) {
console.log(r?.data?.results)
// this closes the oneauth component after successful login
element.handleProfileAuthentication(true);
}
})
.catch((e) => {
//In the event of an error, an error block can be displayed, offering options to retry login or cancel, utilizing the handleProfileAuthentication function.
element.handleProfileAuthentication(false);
});
};
}, []);
-->
Reactivate Login
In this implementation, once the web component is closed, we need to programmatically trigger the authentication process to ensure it can be reactivated as needed. By triggering the authentication manually, we ensure that the user can still be authenticated.
<!--
useEffect(() => {
document.querySelector("hfn-oneauth")?.triggerAuth();
}, []);
-->
Get new active token using refresh token & Logout utils.
<!--
import { getRefreshToken, userLogout } from "hfn-oneauth/main";
// Retrive new token from refresh token
const getActiveToken = async () => {
const params = {
"authUrl":"https://xxx.com",
"realm":"xxx",
"client_id":"xxx"
};
const tokenData = await getRefreshToken(params).catch(() => {
// console.log(e);
});
console.log(tokenData);
};
// Logout - Clear keycloak session
const logout = async () => {
const params = {
"authUrl":"https://xxx.com",
"realm":"xxx",
"client_id":"xxx"
};
const subPath ="yoga"
const res = userLogout(params, subPath);
if (!res?.error) {
// logout success
}
};
<Button onClick={getActiveToken} className="logout-btn btn-cls">
Active Token
</Button>
<Button onClick={logout} className="logout-btn btn-cls">
Logout
</Button>
-->
NextJS Implementation
npm i hfn-oneauth
In NextJS App:
layout.jsx
<!--
const hfnAuth = useRef();
React.useEffect(() => {
import("hfn-oneauth/main");
});
return (
<hfn-oneauth config='{"authUrl":"https://xxx.com","realm":"xxx","client_id":"xxx"}' showCancel="true" authType="on-demand" /></hfn-oneauth>
);
-->
Handle authentication in "/oneauth/authorization" page
Create a /oneauth/authorization
route in your application to manage post-login processes, handle the authorization logic, and redirect the user appropriately after authentication.
<!--
useEffect(() => {
// After successful login, We will get Auth token from the below callback method. Using this token we can fetch SRCM profile information.
hfnAuth.current.loginCallback = (res) => {
fetch(`{baseURL}/xxx/me/`, {
headers: {
Accept: "application/json",
Authorization: `Bearer res?.access_token`,
}
})
.then((r) => {
if (r?.data?.results.length > 0) {
console.log(r?.data?.results)
// this closes the oneauth component after successful login
element.handleProfileAuthentication(true);
}
})
.catch((e) => {
//In the event of an error, an error block can be displayed, offering options to retry login or cancel, utilizing the handleProfileAuthentication function.
hfnAuth.current.handleProfileAuthentication(false);
});
};
}, []);
Reactivate Login
In this implementation, once the web component is closed, we need to programmatically trigger the authentication process to ensure it can be reactivated as needed. By triggering the authentication manually, we ensure that the user can still be authenticated.
<!--
useEffect(() => {
document.querySelector("hfn-oneauth")?.triggerAuth();
}, []);
-->
Get new active token using refresh token & Logout utils.
<!--
// Retrive new token from refresh token
const getActiveToken = async () => {
if (typeof window !== "undefined") {
const { getRefreshToken } = await import("hfn-oneauth/main");
const params = {
"authUrl":"https://xxx.com",
"realm":"xxx",
"client_id":"xxx"
};
const tokenData = await getRefreshToken(params).catch(() => {
// console.log(e);
});
console.log(tokenData);
}
};
// Logout - Clear keycloak session
const logout = async () => {
const params = {
"authUrl":"https://xxx.com",
"realm":"xxx",
"client_id":"xxx"
};
const subPath ="yoga"
if (typeof window !== "undefined") {
const { userLogout } = await import("hfn-oneauth/main");
const res = await userLogout(params,subPath);
if (!res?.error) {
// Successfully logout
}
}
};
<Button onClick={getActiveToken} className="logout-btn btn-cls">
Active Token
</Button>
<Button onClick={logout} className="logout-btn btn-cls">
Logout
</Button>
-->