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

feat: adding support for refresh tokens #51

Merged
merged 2 commits into from
Jun 27, 2024
Merged
Show file tree
Hide file tree
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
3 changes: 2 additions & 1 deletion examples/code-flow/src/main.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useAuth } from "@versini/auth-provider";
import { AUTH_TYPES, useAuth } from "@versini/auth-provider";
import { Button, Footer, Header, Main } from "@versini/ui-components";
import { Flexgrid, FlexgridItem } from "@versini/ui-system";
import { useState } from "react";
Expand All @@ -12,6 +12,7 @@ export const App = ({ timeout }: { timeout: string }) => {
const response = await login(
process.env.PUBLIC_TEST_USER as string,
process.env.PUBLIC_TEST_USER_PASSWORD as string,
AUTH_TYPES.CODE,
);
if (!response) {
console.error(`==> [${Date.now()}] : `, "Login failed");
Expand Down
3 changes: 2 additions & 1 deletion packages/auth-common/src/components/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export const HEADERS = {

export const JWT = {
ALG: "RS256",
USER_ID_KEY: "_id",
USER_ID_KEY: "sub",
TOKEN_ID_KEY: "__raw",
NONCE_KEY: "_nonce",
ISSUER: "gizmette.com",
Expand All @@ -30,6 +30,7 @@ awIDAQAB
export const TOKEN_EXPIRATION = {
ACCESS: "5m",
ID: "90d",
REFRESH: "90d",
};

export const API_TYPE = {
Expand Down
3 changes: 1 addition & 2 deletions packages/auth-common/src/components/pkce.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,5 @@ export async function verifyChallenge(
code_verifier: string,
expectedChallenge: string,
) {
const actualChallenge = await generateCodeChallenge(code_verifier);
return actualChallenge === expectedChallenge;
return expectedChallenge === (await generateCodeChallenge(code_verifier));
}
2 changes: 1 addition & 1 deletion packages/auth-provider/src/common/types.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export type ServiceCallProps = {
params: any;
clientId: string;
type: "authenticate" | "logout" | (string & {});
};

Expand All @@ -15,7 +16,6 @@ export type AuthState = {
isAuthenticated: boolean;
logoutReason?: string;
userId?: string;
idTokenClaims?: any;
};

export type AuthContextProps = {
Expand Down
66 changes: 57 additions & 9 deletions packages/auth-provider/src/common/utilities.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
API_TYPE,
AUTH_TYPES,
HEADERS,
JWT,
Expand All @@ -10,12 +11,12 @@ import type { ServiceCallProps } from "./types";

const isProd = process.env.NODE_ENV === "production";
const isDev = !isProd;
const API_TYPE = {
AUTHENTICATE: "authenticate",
LOGOUT: "logout",
};

export const serviceCall = async ({ type, params = {} }: ServiceCallProps) => {
export const serviceCall = async ({
type,
clientId,
params = {},
}: ServiceCallProps) => {
try {
const response = await fetch(
isDev ? `${API_ENDPOINT.dev}/${type}` : `${API_ENDPOINT.prod}/${type}`,
Expand All @@ -24,7 +25,7 @@ export const serviceCall = async ({ type, params = {} }: ServiceCallProps) => {
method: "POST",
headers: {
"Content-Type": "application/json",
[HEADERS.CLIENT_ID]: `${params.clientId}`,
[HEADERS.CLIENT_ID]: `${clientId}`,
},
body: JSON.stringify(params),
},
Expand All @@ -45,18 +46,26 @@ export const serviceCall = async ({ type, params = {} }: ServiceCallProps) => {
return { status: 500, data: [] };
}
};

export const logoutUser = async ({
idToken,
accessToken,
refreshToken,
clientId,
}: { idToken: string; accessToken: string; clientId: string }) => {
}: {
idToken: string;
accessToken: string;
refreshToken: string;
clientId: string;
}) => {
try {
const response = await serviceCall({
type: API_TYPE.LOGOUT,
clientId,
params: {
idToken,
accessToken,
clientId,
refreshToken,
},
});
return {
Expand All @@ -76,24 +85,30 @@ export const authenticateUser = async ({
nonce,
type,
sessionExpiration,
code,
code_verifier,
}: {
username: string;
password: string;
clientId: string;
nonce: string;
type?: string;
sessionExpiration?: string;
code?: string;
code_verifier?: string;
}) => {
try {
const response = await serviceCall({
type: API_TYPE.AUTHENTICATE,
clientId,
params: {
type: type || AUTH_TYPES.ID_AND_ACCESS_TOKEN,
username,
password,
sessionExpiration,
clientId,
nonce,
code,
code_verifier,
},
});
const jwt = await verifyAndExtractToken(response.data.idToken);
Expand All @@ -105,6 +120,7 @@ export const authenticateUser = async ({
return {
idToken: response.data.idToken,
accessToken: response.data.accessToken,
refreshToken: response.data.refreshToken,
userId: jwt.payload[JWT.USER_ID_KEY] as string,
status: true,
};
Expand All @@ -119,3 +135,35 @@ export const authenticateUser = async ({
};
}
};

export const getPreAuthCode = async ({
nonce,
clientId,
code_challenge,
}: { clientId: string; nonce: string; code_challenge: string }) => {
try {
const response = await serviceCall({
type: API_TYPE.CODE,
clientId,
params: {
type: AUTH_TYPES.CODE,
nonce,
code_challenge,
},
});
if (response.data.code) {
return {
status: true,
code: response.data.code,
};
} else {
return {
status: false,
};
}
} catch (_error) {
return {
status: false,
};
}
};
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,4 @@ export const AuthContext = createContext<AuthContextProps>({
getAccessToken: stub,
getIdToken: stub,
logoutReason: "",
idTokenClaims: null,
});
97 changes: 74 additions & 23 deletions packages/auth-provider/src/components/AuthProvider/AuthProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { JWT, verifyAndExtractToken } from "@versini/auth-common";
import {
AUTH_TYPES,
JWT,
pkceChallengePair,
verifyAndExtractToken,
} from "@versini/auth-common";
aversini marked this conversation as resolved.
Show resolved Hide resolved
import { useLocalStorage } from "@versini/ui-hooks";
import { useCallback, useEffect, useState } from "react";
import { v4 as uuidv4 } from "uuid";
Expand All @@ -10,7 +15,11 @@ import {
LOGOUT_SESSION,
} from "../../common/constants";
import type { AuthProviderProps, AuthState } from "../../common/types";
import { authenticateUser, logoutUser } from "../../common/utilities";
import {
authenticateUser,
getPreAuthCode,
logoutUser,
} from "../../common/utilities";
import { AuthContext } from "./AuthContext";

export const AuthProvider = ({
Expand All @@ -24,40 +33,42 @@ export const AuthProvider = ({
const [accessToken, setAccessToken, , removeAccessToken] = useLocalStorage({
key: `${LOCAL_STORAGE_PREFIX}::${clientId}::@@access@@`,
});
const [refreshToken, setRefreshToken, , removeRefreshToken] = useLocalStorage(
{
key: `${LOCAL_STORAGE_PREFIX}::${clientId}::@@refresh@@`,
},
);
const [, setNonce, , removeNonce] = useLocalStorage({
key: `${LOCAL_STORAGE_PREFIX}::${clientId}::@@nonce@@`,
});

const [authState, setAuthState] = useState<AuthState>({
isLoading: true,
isAuthenticated: false,
logoutReason: "",
userId: "",
idTokenClaims: null,
logoutReason: "",
});

const removeStateAndLocalStorage = useCallback(
(logoutReason?: string) => {
setAuthState({
isLoading: false,
isAuthenticated: false,
logoutReason: logoutReason || EXPIRED_SESSION,
userId: "",
idTokenClaims: null,
logoutReason: logoutReason || EXPIRED_SESSION,
});
removeIdToken();
removeAccessToken();
removeRefreshToken();
removeNonce();
},
[removeIdToken, removeAccessToken, removeNonce],
[removeIdToken, removeAccessToken, removeNonce, removeRefreshToken],
);

/**
* This effect is responsible to set the authentication state based on the
* idToken stored in the local storage. It is used when the page is being
* first loaded or refreshed.
* NOTE: we are extending the state with the idTokenClaims to store the
* idToken "string" and other claims in the state.
*/
useEffect(() => {
if (authState.isLoading && idToken !== null) {
Expand All @@ -68,27 +79,25 @@ export const AuthProvider = ({
setAuthState({
isLoading: false,
isAuthenticated: true,
logoutReason: "",
userId: jwt.payload[JWT.USER_ID_KEY] as string,
idTokenClaims: {
...jwt?.payload,
[JWT.TOKEN_ID_KEY]: idToken,
},
logoutReason: "",
});
} else {
removeStateAndLocalStorage(EXPIRED_SESSION);
await logoutUser({
idToken: idToken,
accessToken: accessToken,
clientId: clientId,
idToken,
accessToken,
refreshToken,
clientId,
});
}
} catch (_error) {
removeStateAndLocalStorage(EXPIRED_SESSION);
await logoutUser({
idToken: idToken,
accessToken: accessToken,
clientId: clientId,
idToken,
accessToken,
refreshToken,
clientId,
});
}
})();
Expand All @@ -97,6 +106,7 @@ export const AuthProvider = ({
authState.isLoading,
accessToken,
idToken,
refreshToken,
clientId,
removeStateAndLocalStorage,
]);
Expand All @@ -108,6 +118,45 @@ export const AuthProvider = ({
): Promise<boolean> => {
const _nonce = uuidv4();
setNonce(_nonce);

if (type === AUTH_TYPES.CODE) {
const { code_verifier, code_challenge } = await pkceChallengePair();

const preResponse = await getPreAuthCode({
nonce: _nonce,
clientId,
code_challenge,
});
if (preResponse.status) {
// we received the auth code, now we need to exchange it for the tokens
const response = await authenticateUser({
username,
password,
clientId,
sessionExpiration,
nonce: _nonce,
type,
code: preResponse.code,
code_verifier,
});
if (response.status) {
setIdToken(response.idToken);
setAccessToken(response.accessToken);
setRefreshToken(response.refreshToken);
setAuthState({
isLoading: false,
isAuthenticated: true,
userId: response.userId,
logoutReason: "",
});
return true;
}
removeStateAndLocalStorage(LOGIN_ERROR);
return false;
}
return false;
}

const response = await authenticateUser({
username,
password,
Expand All @@ -119,6 +168,7 @@ export const AuthProvider = ({
if (response.status) {
setIdToken(response.idToken);
setAccessToken(response.accessToken);
setRefreshToken(response.refreshToken);
setAuthState({
isLoading: false,
isAuthenticated: true,
Expand All @@ -133,9 +183,10 @@ export const AuthProvider = ({
const logout = async () => {
removeStateAndLocalStorage(LOGOUT_SESSION);
await logoutUser({
idToken: idToken,
accessToken: accessToken,
clientId: clientId,
idToken,
accessToken,
refreshToken,
clientId,
});
};

Expand Down