Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add keycloak token verification #1314

Merged
merged 2 commits into from
Oct 31, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 59 additions & 44 deletions src/services/AuthService.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Backdrop, CircularProgress, Theme, Typography } from '@mui/material';
import { KeycloakTokenParsed } from 'keycloak-js';
import ky, { HTTPError } from 'ky';
import { KyInstance } from 'ky/distribution/types/ky';
import { useSnackbar } from 'notistack';
Expand Down Expand Up @@ -177,52 +178,66 @@ const Auth = ({ children }: GenericContextProviderProps) => {
}, [demoMode, isServerReachable, user]);

const tokenVerification = useCallback(() => {
if (!initialized || !keycloak.authenticated) return;
const username = keycloak.tokenParsed?.preferred_username;
const checkPlgridAccessServices: (
token: KeycloakTokenParsed | undefined
) => Promise<void> = token => {
const yaptideServices = ['PLG_YAPTIDE_ACCESS'];

/**
* TODO: Check if user is authorized to use this application (e.g. by checking if user is in a certain group)
*/
const validUser = true;
const validUser = yaptideServices.every(
service => token?.plgridAccessServices?.includes(service)
grzanka marked this conversation as resolved.
Show resolved Hide resolved
);

if (!validUser)
openRejectKeycloakDialog({
reason: 'You are not authorized to use this application.',
keycloakAuth: { keycloak, initialized }
});
else if (initialized)
kyRef
.post(`auth/keycloak`, {
headers: {
Authorization: `Bearer ${keycloak.token}`
},
json: {
username
}
})
.json<ResponseAuthLogin>()
.then(({ accessExp }) => {
setUser(prev =>
prev?.username === username
? prev
: {
username,
source: 'keycloak'
}
);
setRefreshInterval(getRefreshDelay(accessExp));
})
.catch((err: HTTPError) => {
setUser(null);
setRefreshInterval(undefined);
openRejectKeycloakDialog({
reason:
err.response?.status === 403
? 'You are not authorized to use this application.'
: err.message,
keycloakAuth: { keycloak, initialized }
if (validUser) return Promise.resolve();
else
return Promise.reject(
`Your account does not have access to appropriate services. Services required: ${yaptideServices}`
);
};

if (!initialized || !keycloak.authenticated) return;

checkPlgridAccessServices(keycloak.tokenParsed)
.then(() => {
const username = keycloak.tokenParsed?.preferred_username;
kyRef
.post(`auth/keycloak`, {
headers: {
Authorization: `Bearer ${keycloak.token}`
},
json: {
username
}
})
.json<ResponseAuthLogin>()
.then(({ accessExp }) => {
setUser(prev =>
prev?.username === username
? prev
: {
username,
source: 'keycloak'
}
);
setRefreshInterval(getRefreshDelay(accessExp));
})
.catch((err: HTTPError) => {
setUser(null);
setRefreshInterval(undefined);
openRejectKeycloakDialog({
reason:
err.response?.status === 403
? 'You are not authorized to use this application.'
: err.message,
keycloakAuth: { keycloak, initialized }
});
});
})
.catch(reason => {
openRejectKeycloakDialog({
reason,
keycloakAuth: { keycloak, initialized }
});
});
}, [initialized, keycloak, kyRef, openRejectKeycloakDialog]);

useEffect(() => {
Expand Down Expand Up @@ -269,7 +284,7 @@ const Auth = ({ children }: GenericContextProviderProps) => {
);

const tokenRefresh = useCallback(() => {
if (!initialized) return Promise.resolve();
if (!initialized || user?.source !== 'keycloak') return Promise.resolve();

return keycloak
.updateToken(300) // 5 minutes in seconds minimum remaining lifetime for token before refresh is allowed
Expand All @@ -281,7 +296,7 @@ const Auth = ({ children }: GenericContextProviderProps) => {
);
})
.catch(reason => {});
}, [enqueueSnackbar, keycloak, initialized]);
}, [initialized, user?.source, keycloak, enqueueSnackbar]);

useIntervalAsync(
tokenRefresh,
Expand Down
Loading