From 39c843d622eeec4208aad224d98b91dcf4fad2fd Mon Sep 17 00:00:00 2001 From: Kevin Gao Date: Wed, 27 Dec 2023 14:51:34 -0800 Subject: [PATCH 1/5] added descope sample app --- with-descope/App.js | 122 +++++++++++++++++++++++++++++++++++ with-descope/README.md | 36 +++++++++++ with-descope/babel.config.js | 6 ++ with-descope/package.json | 23 +++++++ 4 files changed, 187 insertions(+) create mode 100644 with-descope/App.js create mode 100644 with-descope/README.md create mode 100644 with-descope/babel.config.js create mode 100644 with-descope/package.json diff --git a/with-descope/App.js b/with-descope/App.js new file mode 100644 index 00000000..dc055854 --- /dev/null +++ b/with-descope/App.js @@ -0,0 +1,122 @@ +import "core-js/stable/atob"; + +import * as React from "react"; +import * as WebBrowser from "expo-web-browser"; +import * as AuthSession from "expo-auth-session"; +import { Alert, Text, Button, View, StyleSheet } from "react-native"; +import { jwtDecode } from "jwt-decode"; + +WebBrowser.maybeCompleteAuthSession(); + +// Replace with your own Descope Project ID +const descopeProjectId = ""; +const descopeUrl = `https://api.descope.com/${descopeProjectId}`; +const redirectUri = AuthSession.makeRedirectUri(); + +export default function App() { + const [authTokens, setAuthTokens] = React.useState(null); + const [userInfo, setUserInfo] = React.useState(null); + const discovery = AuthSession.useAutoDiscovery(descopeUrl); + + const [request, response, promptAsync] = AuthSession.useAuthRequest( + { + clientId: descopeProjectId, + responseType: AuthSession.ResponseType.Code, + redirectUri, + usePKCE: true, + scopes: ["openid", "profile", "email"], + }, + discovery + ); + + React.useEffect(() => { + const exchangeFn = async (exchangeTokenReq) => { + try { + const exchangeTokenResponse = await AuthSession.exchangeCodeAsync( + exchangeTokenReq, + discovery + ); + setAuthTokens(exchangeTokenResponse); + } catch (error) { + console.error(error); + } + }; + if (response) { + if (response.error) { + Alert.alert( + "Authentication error", + response.params.error_description || "something went wrong" + ); + return; + } + if (response.type === "success") { + exchangeFn({ + clientId: descopeProjectId, + code: response.params.code, + redirectUri, + extraParams: { + code_verifier: request.codeVerifier, + }, + }); + } + } + }, [discovery, request, response]); + + React.useEffect(() => { + if (authTokens && authTokens.accessToken) { + const decodedToken = jwtDecode(authTokens.accessToken); + setUserInfo(decodedToken); + } + }, [authTokens]); + + const logout = async () => { + const revokeResponse = await AuthSession.revokeAsync( + { + clientId: descopeProjectId, + token: authTokens.refreshToken, + }, + discovery + ); + if (revokeResponse) { + setAuthTokens(null); + } + }; + + return ( + + {authTokens ? ( + <> + + Welcome, {userInfo ? userInfo.email : "User"}! + +