Skip to content

Instantly share code, notes, and snippets.

@perisicnikola37
Last active March 27, 2025 15:57
Show Gist options
  • Save perisicnikola37/076df0f7fd2d24637efe229031d1db86 to your computer and use it in GitHub Desktop.
Save perisicnikola37/076df0f7fd2d24637efe229031d1db86 to your computer and use it in GitHub Desktop.
How I used TypeScript State Synchronization in Enterprise Banking Application
const getCustomClaims = async (): Promise<CustomClaims | null> => {
const user = await userManager.getUser();
if (user && user.access_token) {
const jwtToken = user.access_token;
const decodedToken = JSON.parse(atob(jwtToken.split(".")[1]));
const oidcKey = `${KEYCLOAK_URL}:${keycloakConfig.clientId}`;
const currentClaims = JSON.parse(sessionStorage.getItem(oidcKey) || "{}");
const authorities = decodedToken?.resource_access?.[KEYCLOAK_REALM_CLIENT_ID]?.roles || [];
if (!currentClaims.profile) {
currentClaims.profile = {};
}
currentClaims.profile["authorities"] = authorities;
sessionStorage.setItem(oidcKey, JSON.stringify(currentClaims));
return currentClaims;
}
return null;
};
const getCustomClaims = async (): Promise<CustomClaims | null> => {
const user = await userManager.getUser();
// old code
const authoritiesUpdatedEvent = new CustomEvent(
AUTHORITIES_UPDATED_EVENT,
detail: { authorities },
);
window.dispatchEvent(authoritiesUpdatedEvent);
return currentClaims;
)
return null;
}
{
"session_state": "abc123-def456-ghi789-jkl012",
"token_type": "Bearer",
"scope": "openid profile",
"expires_at": 1899999999
}
const { user } = useAuth();
const [authorities, setAuthorities] = useState<string[]>([]);
useEffect(() => {
if (user?.profile?.authorities) {
setAuthorities(user.profile.authorities as string[]);
}
}, [user]);
// this is required for the first render to initialize data
useEffect(() => {
const updateAuthorities = async () => {
const oidcKey = `${KEYCLOAK_URL}:${KEYCLOAK_REALM_CLIENT_ID}`;
const storedUserData = JSON.parse(
sessionStorage.getItem(oidcKey) || "{}",
);
const storedAuthorities =
storedUserData?.profile?.["authorities"] || [];
setAuthorities(storedAuthorities);
};
updateAuthorities();
userManager.events.addUserLoaded(handleUserLoaded);
return () => {
userManager.events.removeUserLoaded(handleUserLoaded);
};
}, []);
// other code
return (
<tbody>
{authorities.map((permission) => (
<tr key={permission}>
<td>
{formatPermissionName(permission)}
</td>
</tr>
))}
</tbody>
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment