hfnauth
v0.3.0
Published
HFN Auth web component
Readme
HFN Auth web component
The hfnAuth 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-auth
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("hfnauth").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 /hfnauth/authorization. After successful authentication through HFN Auth, the user is redirected to the /hfnauth/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("hfnauth");
// 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('hfnauth');
// 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 hfnauth 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-auth config='{"authUrl":"https://xxx.com","realm":"xxx","client_id":"xxx"}' showCancel="true"/></hfn-auth>
</div>
</body>
</html>
-->React & Gatsby Implementation
npm i hfnauth
In React or Gatsby App:
App.jsx or layout.jsx
<!--
const hfnAuth = useRef();
React.useEffect(() => {
import("hfnauth/main");
});
return (
<hfn-auth config='{"authUrl":"https://xxx.com","realm":"xxx","client_id":"xxx"}' showCancel="true" authType="on-demand" /></hfn-auth>
);
-->Handle authentication in "/hfnauth/authorization" page
Create a /hfnauth/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, use the baseurl, xclientId and queryParams to fetch SRCM profile information.
const { getSRCMProfile } = await import("hfnauth/main");
const resData = await getSRCMProfile({
srcmBaseURL: `${baseURL}/`,
xClientId: {xClientId},
queryParams : ['key1', "key2"].join(','),
});
try{
if (resData?.data)
{
console.log(r?.data?.results);
handleProfileAuthentication(true);
}
}
catch{
handleProfileAuthentication(false);
}
}, []);
-->Handle Unauthorized or Other alerts in "/hfnauth/authorization" Page
On the /hfnauth/authorization route in your application, handle unauthorized access logic and display an appropriate alert or error prompt to the end user.
<!--
document.querySelector("hfnauth").handleErrorMessage(
"You dont have neccessary permissions. Please contact adminstrator.", // Error or alert message to display in the modal popup
({ okClicked }) => {
if (okClicked) {
handleProfileAuthentication(true);
navigate({landing page path});
}
},
{
showOkBtn: true,
showCancel: false,
showRetryBtn : false,
btnText: "Okay",
}
);
-->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("hfnauth")?.triggerAuth();
}, []);
-->Get new active token using refresh token & Logout utils.
<!--
import { getRefreshToken, userLogout } from "hfnauth/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 hfnauth
In NextJS App:
layout.jsx
<!--
const hfnAuth = useRef();
React.useEffect(() => {
import("hfnauth/main");
});
return (
<hfn-auth config='{"authUrl":"https://xxx.com","realm":"xxx","client_id":"xxx"}' showCancel="true" authType="on-demand" /></hfn-auth>
);
-->Handle authentication in "/hfnauth/authorization" page
Create a /hfnauth/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, use the baseurl, xclientId and queryParams to fetch SRCM profile information.
const { getSRCMProfile } = await import("hfnauth/main");
const resData = await getSRCMProfile({
srcmBaseURL: `${baseURL}/`,
xClientId: {xClientId},
queryParams : ['key1', "key2"].join(','),
});
try{
if (resData?.data)
{
console.log(r?.data?.results);
handleProfileAuthentication(true);
}
}
catch{
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("hfnauth")?.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("hfnauth/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("hfnauth/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>
-->Handle Unauthorized or Other alerts in "/hfnauth/authorization" Page
On the /hfnauth/authorization route in your application, after receiving a successful response from the SRCM API, handle unauthorized access logic and display an appropriate alert or error prompt to the end user.
<!--
document.querySelector("hfnauth").handleErrorMessage(
"You dont have neccessary permissions. Please contact adminstrator.", // Error or alert message to display in the modal popup
({ okClicked }) => {
if (okClicked) {
handleProfileAuthentication(true);
navigate({landing page path});
}
},
{
showOkBtn: true,
showCancel: false,
showRetryBtn : false,
btnText: "Okay",
}
);
-->