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
Changes from 1 commit
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";
@@ -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");
1 change: 1 addition & 0 deletions packages/auth-common/src/components/constants.ts
Original file line number Diff line number Diff line change
@@ -30,6 +30,7 @@ awIDAQAB
export const TOKEN_EXPIRATION = {
ACCESS: "5m",
ID: "90d",
REFRESH: "90d",
};

export const API_TYPE = {
3 changes: 1 addition & 2 deletions packages/auth-common/src/components/pkce.ts
Original file line number Diff line number Diff line change
@@ -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));
}
1 change: 1 addition & 0 deletions 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 & {});
};

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,
@@ -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}`,
@@ -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),
},
@@ -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 {
@@ -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);
@@ -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,
};
@@ -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,
};
}
};
82 changes: 70 additions & 12 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";
@@ -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 = ({
@@ -24,6 +33,11 @@ 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@@`,
});
@@ -47,9 +61,10 @@ export const AuthProvider = ({
});
removeIdToken();
removeAccessToken();
removeRefreshToken();
removeNonce();
},
[removeIdToken, removeAccessToken, removeNonce],
[removeIdToken, removeAccessToken, removeNonce, removeRefreshToken],
);

/**
@@ -78,17 +93,19 @@ export const AuthProvider = ({
} 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,
});
}
})();
@@ -97,6 +114,7 @@ export const AuthProvider = ({
authState.isLoading,
accessToken,
idToken,
refreshToken,
clientId,
removeStateAndLocalStorage,
]);
@@ -108,6 +126,44 @@ 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,
});
return true;
}
removeStateAndLocalStorage(LOGIN_ERROR);
return false;
}
return false;
}

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