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!: add OAuth2 support #834

Open
wants to merge 9 commits into
base: 0.43
Choose a base branch
from
Open
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
2 changes: 2 additions & 0 deletions examples/for-tests/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +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-oidc-context": "^3.1.0",
"react-router-dom": "6.11.2",
"react-scripts": "^5.0.1"
},
Expand Down
16 changes: 3 additions & 13 deletions examples/for-tests/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import Multitenancy from "supertokens-auth-react/recipe/multitenancy";
import UserRoles from "supertokens-auth-react/recipe/userroles";
import MultiFactorAuth from "supertokens-auth-react/recipe/multifactorauth";
import TOTP from "supertokens-auth-react/recipe/totp";
import OAuth2Provider from "supertokens-auth-react/recipe/oauth2provider";

import axios from "axios";
import { useSessionContext } from "supertokens-auth-react/recipe/session";
Expand All @@ -27,6 +28,7 @@ import { logWithPrefix } from "./logWithPrefix";
import { ErrorBoundary } from "./ErrorBoundary";
import { useNavigate } from "react-router-dom";
import { getTestContext, getEnabledRecipes, getQueryParams } from "./testContext";
import { getApiDomain, getWebsiteDomain } from "./config";

const loadv5RRD = window.localStorage.getItem("react-router-dom-is-v5") === "true";
if (loadv5RRD) {
Expand All @@ -43,18 +45,6 @@ const withRouter = function (Child) {

Session.addAxiosInterceptors(axios);

export function getApiDomain() {
const apiPort = process.env.REACT_APP_API_PORT || 8082;
const apiUrl = process.env.REACT_APP_API_URL || `http://localhost:${apiPort}`;
return apiUrl;
}

export function getWebsiteDomain() {
const websitePort = process.env.REACT_APP_WEBSITE_PORT || 3031;
const websiteUrl = process.env.REACT_APP_WEBSITE_URL || `http://localhost:${websitePort}`;
return getQueryParams("websiteDomain") ?? websiteUrl;
}

/*
* Use localStorage for tests configurations.
*/
Expand Down Expand Up @@ -419,6 +409,7 @@ let recipeList = [
console.log(`ST_LOGS SESSION ON_HANDLE_EVENT ${ctx.action}`);
},
}),
OAuth2Provider.init(),
];

let enabledRecipes = getEnabledRecipes();
Expand Down Expand Up @@ -801,7 +792,6 @@ function getSignInFormFields(formType) {
id: "test",
},
];
return;
}
}

Expand Down
7 changes: 6 additions & 1 deletion examples/for-tests/src/AppWithReactDomRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@ import { EmailPasswordPreBuiltUI } from "supertokens-auth-react/recipe/emailpass
import { PasswordlessPreBuiltUI } from "supertokens-auth-react/recipe/passwordless/prebuiltui";
import { EmailVerificationPreBuiltUI } from "supertokens-auth-react/recipe/emailverification/prebuiltui";
import { ThirdPartyPreBuiltUI, SignInAndUpCallback } from "supertokens-auth-react/recipe/thirdparty/prebuiltui";
import { OAuth2ProviderPreBuiltUI } from "supertokens-auth-react/recipe/oauth2provider/prebuiltui";
import { AccessDeniedScreen } from "supertokens-auth-react/recipe/session/prebuiltui";
import { MultiFactorAuthPreBuiltUI } from "supertokens-auth-react/recipe/multifactorauth/prebuiltui";
import { TOTPPreBuiltUI } from "supertokens-auth-react/recipe/totp/prebuiltui";
import { BaseComponent, Home, Contact, Dashboard, DashboardNoAuthRequired } from "./App";
import { getEnabledRecipes, getTestContext } from "./testContext";
import OAuth2Page from "./OAuth2Page";

function AppWithReactDomRouter(props) {
/**
Expand All @@ -30,7 +32,7 @@ function AppWithReactDomRouter(props) {
const emailVerificationMode = window.localStorage.getItem("mode") || "OFF";
const websiteBasePath = window.localStorage.getItem("websiteBasePath") || undefined;

let recipePreBuiltUIList = [TOTPPreBuiltUI];
let recipePreBuiltUIList = [TOTPPreBuiltUI, OAuth2ProviderPreBuiltUI];
if (enabledRecipes.some((r) => r.startsWith("thirdparty"))) {
recipePreBuiltUIList.push(ThirdPartyPreBuiltUI);
}
Expand Down Expand Up @@ -172,6 +174,9 @@ function AppWithReactDomRouter(props) {
}
/>
)}

<Route path="/oauth/login" element={<OAuth2Page />} />
<Route path="/oauth/callback" element={<OAuth2Page />} />
</Routes>
</BaseComponent>
</Router>
Expand Down
91 changes: 91 additions & 0 deletions examples/for-tests/src/OAuth2Page.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { AuthProvider, useAuth } from "react-oidc-context";
import { getApiDomain, getWebsiteDomain } from "./config";

// NOTE: For convenience, the same page/component handles both login initiation and callback.
// Separate pages for login and callback are not required.

const scopes = window.localStorage.getItem("oauth2-scopes") ?? "profile openid offline_access email";
const extraConfig = JSON.parse(window.localStorage.getItem("oauth2-extra-config") ?? "{}");
const extraSignInParams = JSON.parse(window.localStorage.getItem("oauth2-extra-sign-in-params") ?? "{}");
const extraSignOutParams = JSON.parse(window.localStorage.getItem("oauth2-extra-sign-out-params") ?? "{}");

const oidcConfig = {
client_id: window.localStorage.getItem("oauth2-client-id"),
authority: `${getApiDomain()}/auth`,
response_type: "code",
redirect_uri: `${getWebsiteDomain()}/oauth/callback`,
scope: scopes ? scopes : "profile openid offline_access email",
...extraConfig,
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 { signinRedirect, signinSilent, signoutSilent, signoutRedirect, user, error } = useAuth();

return (
<div>
<h1 style={{ textAlign: "center" }}>OAuth2 Login Test</h1>
<div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
{error && <p id="oauth2-error-message">Error: {error.message}</p>}
{user && (
<>
<pre id="oauth2-token-data">{JSON.stringify(user.profile, null, 2)}</pre>
<button id="oauth2-logout-button" onClick={() => signoutSilent(extraSignOutParams)}>
Logout
</button>
<button id="oauth2-logout-button-redirect" onClick={() => signoutRedirect(extraSignOutParams)}>
Logout (Redirect)
</button>
</>
)}
<button id="oauth2-login-button" onClick={() => signinRedirect(extraSignInParams)}>
Login With SuperTokens
</button>
<button id="oauth2-login-button-silent" onClick={() => signinSilent(extraSignInParams)}>
Login With SuperTokens (silent)
</button>
<button
id="oauth2-login-button-prompt-login"
onClick={() =>
signinRedirect({
prompt: "login",
...extraSignInParams,
})
}>
Login With SuperTokens (prompt=login)
</button>
<button
id="oauth2-login-button-max-age-3"
onClick={() =>
signinRedirect({
max_age: 3,
...extraSignInParams,
})
}>
Login With SuperTokens (max_age=3)
</button>
<button
id="oauth2-login-button-prompt-none"
onClick={() =>
signinRedirect({
prompt: "none",
...extraSignInParams,
})
}>
Login With SuperTokens (prompt=none)
</button>
</div>
</div>
);
}

export default function OAuth2Page() {
return (
<AuthProvider {...oidcConfig}>
<AuthPage />
</AuthProvider>
);
}
13 changes: 13 additions & 0 deletions examples/for-tests/src/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { getQueryParams } from "./testContext";

export function getApiDomain() {
const apiPort = process.env.REACT_APP_API_PORT || 8082;
const apiUrl = process.env.REACT_APP_API_URL || `http://localhost:${apiPort}`;
return apiUrl;
}

export function getWebsiteDomain() {
const websitePort = process.env.REACT_APP_WEBSITE_PORT || 3031;
const websiteUrl = process.env.REACT_APP_WEBSITE_URL || `http://localhost:${websitePort}`;
return getQueryParams("websiteDomain") ?? websiteUrl;
}
2 changes: 1 addition & 1 deletion hooks/pre-commit.sh
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ else
fi

npm run check-circular-dependencies
circDep=$?
circDep=$?

echo "$(tput setaf 3)* No circular dependencies?$(tput sgr 0)"

Expand Down
5 changes: 4 additions & 1 deletion lib/.eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,10 @@ module.exports = {
],
"@typescript-eslint/naming-convention": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-unused-vars": [2, { vars: "all", args: "all", varsIgnorePattern: "^React$|^jsx$" }],
"@typescript-eslint/no-unused-vars": [
2,
{ vars: "all", args: "all", varsIgnorePattern: "^React$|^jsx$", argsIgnorePattern: "^_" },
],
"@typescript-eslint/prefer-namespace-keyword": "error",
"@typescript-eslint/quotes": ["error", "double"],
"@typescript-eslint/semi": ["error", "always"],
Expand Down
2 changes: 2 additions & 0 deletions lib/build/components/assets/logoutIcon.d.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion lib/build/emailpassword-shared3.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions lib/build/emailpassword.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading