Skip to content

Commit

Permalink
fix: PR changes
Browse files Browse the repository at this point in the history
  • Loading branch information
anku255 committed Aug 2, 2024
1 parent 8540f9e commit d866aa5
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 26 deletions.
3 changes: 2 additions & 1 deletion examples/for-tests/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@
"private": true,
"dependencies": {
"axios": "^0.21.0",
"oidc-client-ts": "^3.0.1",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-oauth2-code-pkce": "^1.20.1",
"react-oidc-context": "^3.1.0",
"react-router-dom": "6.11.2",
"react-scripts": "^5.0.1"
},
Expand Down
37 changes: 20 additions & 17 deletions examples/for-tests/src/OAuth2Page.js
Original file line number Diff line number Diff line change
@@ -1,36 +1,39 @@
import { useContext } from "react";
import { AuthContext, AuthProvider } from "react-oauth2-code-pkce";
import { AuthProvider, useAuth } from "react-oidc-context";
import { getApiDomain, getWebsiteDomain } from "./config";

const authConfig = {
clientId: window.localStorage.getItem("oauth2-client-id"),
authorizationEndpoint: `${getApiDomain()}/auth/oauth2provider/auth`,
tokenEndpoint: `${getApiDomain()}/auth/oauth2provider/token`,
redirectUri: `${getWebsiteDomain()}/oauth2/callback`,
// NOTE: For convenience, the same page/component handles both login initiation and callback.
// Separate pages for login and callback are not required.

const oidcConfig = {
client_id: window.localStorage.getItem("oauth2-client-id"),
authority: `${getApiDomain()}/auth`,
response_type: "code",
redirect_uri: `${getWebsiteDomain()}/oauth2/callback`,
scope: "profile openid offline_access email",
state: Math.random().toString(36).substring(2),
autoLogin: false,
decodeToken: true,
onSigninCallback: async (user) => {
// Clears the response code and other params from the callback url
window.history.replaceState({}, document.title, window.location.pathname);
},
};

function AuthPage() {
const { tokenData, logIn, logOut, error } = useContext(AuthContext);
const { signinRedirect, signoutSilent, user, error } = useAuth();

return (
<div>
<h1 style={{ textAlign: "center" }}>OAuth2 Login Test</h1>
<div>
{tokenData ? (
{user ? (
<div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
<pre id="oauth2-token-data">{JSON.stringify(tokenData, null, 2)}</pre>
<button id="oauth2-logout-button" onClick={() => logOut()}>
<pre id="oauth2-token-data">{JSON.stringify(user.profile, null, 2)}</pre>
<button id="oauth2-logout-button" onClick={() => signoutSilent()}>
Logout
</button>
</div>
) : (
<div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
{error && <p id="oauth2-error-message">Error: {error}</p>}
<button id="oauth2-login-button" onClick={() => logIn()}>
{error && <p id="oauth2-error-message">Error: {error.message}</p>}
<button id="oauth2-login-button" onClick={() => signinRedirect()}>
Login With SuperTokens
</button>
</div>
Expand All @@ -42,7 +45,7 @@ function AuthPage() {

export default function OAuth2Page() {
return (
<AuthProvider authConfig={authConfig}>
<AuthProvider {...oidcConfig}>
<AuthPage />
</AuthProvider>
);
Expand Down
22 changes: 14 additions & 8 deletions test/end-to-end/oauth2provider.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,12 @@ describe("SuperTokens OAuth2Provider", function () {
let browser;
let page;
let consoleLogs = [];
let skipped = false;

before(async function () {
// Skip these tests if running in React 16
if (isReact16()) {
skipped = true;
this.skip();
}

Expand All @@ -68,6 +70,9 @@ describe("SuperTokens OAuth2Provider", function () {
});

after(async function () {
if (skipped) {
return;
}
await browser.close();

await fetch(`${TEST_SERVER_BASE_URL}/after`, {
Expand Down Expand Up @@ -127,7 +132,7 @@ describe("SuperTokens OAuth2Provider", function () {

// Validate token data
const tokenData = await getOAuth2TokenData(page);
assert.deepStrictEqual(tokenData.client_id, client.clientId);
assert.deepStrictEqual(tokenData.aud, [client.clientId]);

// Logout
const logoutButton = await getOAuth2LogoutButton(page);
Expand All @@ -147,8 +152,9 @@ describe("SuperTokens OAuth2Provider", function () {
grantTypes: ["authorization_code", "refresh_token"],
responseTypes: ["code", "id_token"],
skipConsent: true,
// Setting access token lifespan to 3 seconds to force refresh
authorizationCodeGrantAccessTokenLifespan: "3s",
// The library refreshes the token 60 seconds before it expires.
// We set the token lifespan to 63 seconds to force a refresh in 3 seconds.
authorizationCodeGrantAccessTokenLifespan: "63s",
});

await setOAuth2ClientIdInStorage(page, client.clientId);
Expand All @@ -168,19 +174,19 @@ describe("SuperTokens OAuth2Provider", function () {

// Validate token data
const tokenDataAfterLogin = await getOAuth2TokenData(page);
assert.deepStrictEqual(tokenDataAfterLogin.client_id, client.clientId);
assert.deepStrictEqual(tokenDataAfterLogin.aud, [client.clientId]);

// The react-oauth2-code-pkce library refreshes the token in an interval of 10 seconds.
// To force the refresh before that, we wait for 4 seconds and reload the page.
// Although the react-oidc-context library automatically refreshes the
// token, we wait for 4 seconds and reload the page to ensure a refresh.
await waitFor(4000);
await page.reload();
await page.waitForNavigation({ waitUntil: "networkidle0" });

const tokenDataAfterRefresh = await getOAuth2TokenData(page);
assert.deepStrictEqual(tokenDataAfterRefresh.client_id, client.clientId);
assert.deepStrictEqual(tokenDataAfterRefresh.aud, [client.clientId]);

// Validate the token was refreshed
assert(tokenDataAfterLogin.jti !== tokenDataAfterRefresh.jti);
assert(tokenDataAfterLogin.iat !== tokenDataAfterRefresh.iat);
assert(tokenDataAfterLogin.exp < tokenDataAfterRefresh.exp);
});
});
Expand Down
2 changes: 2 additions & 0 deletions test/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -1115,6 +1115,8 @@ export async function createOAuth2Client(input) {
return await resp.json();
}

// For the OAuth2 end-to-end test, we need to provide the created clientId to both the OAuth2 login and callback pages.
// We use localStorage to store the clientId instead of query params, as it must be available on the callback page as well.
export async function setOAuth2ClientIdInStorage(page, clientId) {
return page.evaluate((clientId) => localStorage.setItem("oauth2-client-id", clientId), clientId);
}
Expand Down

0 comments on commit d866aa5

Please sign in to comment.