GithubHelp home page GithubHelp logo

auth0 / auth0-react Goto Github PK

View Code? Open in Web Editor NEW
854.0 22.0 249.0 4.2 MB

Auth0 SDK for React Single Page Applications (SPA)

License: MIT License

JavaScript 7.01% TypeScript 87.79% HTML 5.12% Shell 0.09%
dx-sdk react reactjs authentication spa

auth0-react's Introduction

Auth0 SDK for React Single Page Applications

npm codecov Downloads License CircleCI

📚 Documentation - 🚀 Getting Started - 💻 API Reference - 💬 Feedback

Documentation

  • Quickstart - our interactive guide for quickly adding login, logout and user information to a React app using Auth0.
  • Sample App - a full-fledged React application integrated with Auth0.
  • FAQs - frequently asked questions about the auth0-react SDK.
  • Examples - code samples for common React authentication scenario's.
  • Docs site - explore our docs site and learn more about Auth0.

Getting started

Installation

Using npm

npm install @auth0/auth0-react

Using yarn

yarn add @auth0/auth0-react

Configure Auth0

Create a Single Page Application in the Auth0 Dashboard.

If you're using an existing application, verify that you have configured the following settings in your Single Page Application:

  • Click on the "Settings" tab of your application's page.
  • Scroll down and click on the "Show Advanced Settings" link.
  • Under "Advanced Settings", click on the "OAuth" tab.
  • Ensure that "JsonWebToken Signature Algorithm" is set to RS256 and that "OIDC Conformant" is enabled.

Next, configure the following URLs for your application under the "Application URIs" section of the "Settings" page:

  • Allowed Callback URLs: http://localhost:3000
  • Allowed Logout URLs: http://localhost:3000
  • Allowed Web Origins: http://localhost:3000

These URLs should reflect the origins that your application is running on. Allowed Callback URLs may also include a path, depending on where you're handling the callback.

Take note of the Client ID and Domain values under the "Basic Information" section. You'll need these values in the next step.

Configure the SDK

Configure the SDK by wrapping your application in Auth0Provider:

// src/index.js
import React from 'react';
import { createRoot } from 'react-dom/client';
import { Auth0Provider } from '@auth0/auth0-react';
import App from './App';

const root = createRoot(document.getElementById('app'));

root.render(
  <Auth0Provider
    domain="YOUR_AUTH0_DOMAIN"
    clientId="YOUR_AUTH0_CLIENT_ID"
    authorizationParams={{
      redirect_uri: window.location.origin,
    }}
  >
    <App />
  </Auth0Provider>
);
Instructions for React <18
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Auth0Provider } from '@auth0/auth0-react';
import App from './App';

ReactDOM.render(
  <Auth0Provider
    domain="YOUR_AUTH0_DOMAIN"
    clientId="YOUR_AUTH0_CLIENT_ID"
    authorizationParams={{
      redirect_uri: window.location.origin,
    }}
  >
    <App />
  </Auth0Provider>,
  document.getElementById('app')
);

Use the useAuth0 hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.js
import React from 'react';
import { useAuth0 } from '@auth0/auth0-react';

function App() {
  const { isLoading, isAuthenticated, error, user, loginWithRedirect, logout } =
    useAuth0();

  if (isLoading) {
    return <div>Loading...</div>;
  }
  if (error) {
    return <div>Oops... {error.message}</div>;
  }

  if (isAuthenticated) {
    return (
      <div>
        Hello {user.name}{' '}
        <button onClick={() => logout({ logoutParams: { returnTo: window.location.origin } })}>
          Log out
        </button>
      </div>
    );
  } else {
    return <button onClick={() => loginWithRedirect()}>Log in</button>;
  }
}

export default App;

For more code samples on how to integrate auth0-react SDK in your React application, have a look at our examples.

API reference

Explore public API's available in auth0-react.

Feedback

Contributing

We appreciate feedback and contribution to this repo! Before you get started, please see the following:

Raise an issue

To provide feedback or report a bug, please raise an issue on our issue tracker.

Vulnerability Reporting

Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.


Auth0 Logo

Auth0 is an easy to implement, adaptable authentication and authorization platform. To learn more checkout Why Auth0?

This project is licensed under the MIT license. See the LICENSE file for more info.

auth0-react's People

Contributors

adamjmcgrath avatar aulos avatar crew-security avatar dependabot[bot] avatar evansims avatar ewanharris avatar fossabot avatar frederikprijck avatar idered avatar jameskmonger avatar joshaddington avatar kweiberth avatar lbalmaceda avatar lgtm-com[bot] avatar maxbrokhman avatar mjbcopland avatar nandan-bhat avatar piwysocki avatar rene00 avatar snyk-bot avatar sre-57-opslevel[bot] avatar stefanocaroli avatar stephenkelzer avatar suke avatar thejefe avatar tkiryu avatar tyfrth avatar waxmar avatar widcket avatar ygist avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

auth0-react's Issues

Using Auth with class components

There's very scarce documentation on how to use this library with class components. I found this example:

import React, { Component } from 'react';
import { withAuth0 } from '@auth0/auth0-react';

class Profile extends Component {
  render() {
    const { user } = this.props.auth0;
    return <div>Hello {user.name}</div>;
  }
}

export default withAuth0(Profile);

Now I want to achieve something like this:

import React, { Component } from 'react';
import { withAuth0 } from '@auth0/auth0-react';

class Profile extends Component {
  render() {
    const { user } = this.props.auth0;
    const isAuthenticated = ??? // <---- how do I get this value?
    return isAuthenticated ? renderAuthenticatedUser(user) : renderUnauthenticatedUser();
  }
}

export default withAuth0(Profile);

How do I do this? I've been reading through the docs and scratching my head for quite a while..

Passwordless - Magic link from email

Describe the problem

We've enabled the passwordless (Email) in our auth0 and trying to implement it using this SDK.

We receive the generated magic link from auth0 via email and the magic link goes like ourdomain.com/passwordless/verify_direct?scope=openid&response_type=token&redirect_uri=ourdomain.com/callback&verification_code=350357&connection=email&client_id=OUR_CLIENT_ID&email=MY_EMAIL.

Now when we click on it our app is stuck on the callback url with these params ourdomain.com/callback#access_token=REDACTED&scope=openid&expires_in=7200&token_type=Bearer

Question is if the SDK supports this feature? or is part of the roadmap?

We're aware that the SDK is using auth0-spa-js and it supports passwordless. But the current sdk doesnt expose the Auth0Client. Do you have any suggestions?

Thank you very much

What was the expected behavior?

Successfully login using the magic link

Reproduction

  • Enable passwordless in auth0 dashboard and use email as the option
  • Trigger a magic link to be sent to your email
  • Click on the link

Environment

  • **Version of auth0-react used: latest
  • Which browsers have you tested in?: chrome and safari
  • Which framework are you using, if applicable (Angular, React, etc): React

isAuthenticated and user are null after login

Please do not report security vulnerabilities here. The Responsible Disclosure Program details the procedure for disclosing security issues.

Thank you in advance for helping us to improve this library! Please read through the template below and answer all relevant questions. Your additional work here is greatly appreciated and will help us respond as quickly as possible. For general support or usage questions, use the Auth0 Community or Auth0 Support. Finally, to avoid duplicates, please search existing Issues before submitting one here.

By submitting an Issue to this repository, you agree to the terms within the Auth0 Code of Conduct.

Description

When using Aut0/auth0-react and the useAuth0 hook:

const { isAuthenticated, user, loginWithRedirect, logout } = useAuth0();

After logging in the application isAuthenticated is still false and user is undefined.

Reproduction

Add the package and follow direction on the Auth0 quick start page https://auth0.com/docs/quickstart/spa/react/01-login
login the application and get automatically redirected to the home page.

Where applicable, please include:

import {useAuth0} from "@auth0/auth0-react";

const NavBar = () => {
  const classes = useStyles();
  const { isAuthenticated, loginWithRedirect, logout } = useAuth0();

  console.log(isAuthenticated);

  return (
    <div className={classes.root}>
      <AppBar position="static" className={classes.navBar}>
        <Toolbar>
          <IconButton edge="start" className={classes.menuButton} color="inherit" aria-label="menu">
            <MenuIcon />
          </IconButton>
          <Typography variant="h6" className={classes.title}>
            Child Life Disaster Relief
          </Typography>

          <Button color="inherit" className={classes.button} onClick={logout}>Logout</Button>

          {!isAuthenticated &&
          <Button color="inherit" className={classes.button} onClick={loginWithRedirect}>Login</Button>
          }

        </Toolbar>
      </AppBar>
    </div>
  );
};

export default NavBar;

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { Auth0Provider } from "@auth0/auth0-react";

ReactDOM.render(
  <React.StrictMode>
    <Auth0Provider
      domain={process.env.REACT_APP_DOMAIN}
      clientId={process.env.REACT_APP_CLIENT_ID}
      redirectUri={window.location.origin}
    >
      <App />
    </Auth0Provider>
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
  • Log files (redact/remove sensitive information)
  • Application settings (redact/remove sensitive information)
  • Screenshots

Environment

Versions:

"dependencies": {
    "@auth0/auth0-react": "^1.0.0",
    "@date-io/date-fns": "1.x",
    "@material-ui/core": "^4.11.0",
    "@material-ui/icons": "^4.9.1",
    "@material-ui/styles": "^4.10.0",
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    "date-fns": "^2.15.0",
    "formik": "^2.1.5",
    "formik-material-ui": "^3.0.0-alpha.0",
    "formik-material-ui-pickers": "^0.0.11",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-scripts": "3.4.1"
  },

Can't resolve @auth0/auth0-react

Hi, using the latest version of Create React App and VSCode in Windows 10 with bash as my terminal using auth0 version 2.27.1. I know it's installed because I can check my version in NPM, and because it's in my package.json. However, I get this error "./src/index.js
Module not found: Can't resolve '@auth0/auth0-react' in 'C:\Users\Philip\Desktop\Coding\auth\src'"
when importing "import { Auth0Provider } from "@auth0/auth0-react";".

Thanks!

User is not authenticated on page refresh.

Description

User logs in with loginWithRedirect function. But on refreshing the page useAuth0 returns isAuthenticated as false.
But on calling longinWithRedirect user gets authenticated without any credentials.

Reproduction

I am using google oauth.

Environment

  • **Version of this library used:**1.0.0
  • Browser: Brave

Handling Email Verification within React App

Do you have any examples of handling email verification within a React App using the auth0-react approach?

Is this typically handled from the universal login pages or within the client application?

Currently, we require user to complete email verification in order to log in. We use universal login pages to handle authentication. Once a user signs up they are redirected to our React Application which uses this project. We have an Auth0Provider setup which looks like this:

useEffect(() => {
    const initAuth0 = async () => {
      try {
        const auth0FromHook = await createAuth0Client(initOptions);
        setAuth0(auth0FromHook);

        if (
          window.location.search.includes('code=') &&
          window.location.search.includes('state=')
        ) {
          const { appState } = await auth0FromHook.handleRedirectCallback();
          onRedirectCallback(appState);
        }

        const isUserAuthenticated = await auth0FromHook.isAuthenticated();
        setIsAuthenticated(isUserAuthenticated);

        if (isUserAuthenticated) {
          const resultUser = await auth0FromHook.getUser();
          setUser(resultUser);

          // TODO: We need to get the my account menu item here. We can then get the user info to use.
          Log.info(
            `Authenticated resultUser: ${JSON.stringify(resultUser)}`,
            'Auth0-SPA'
          );
        }

        setLoading(false);
      } catch (error) {
        setLoading(false);
        Log.info('error occurred');
        Log.info(error);
      }
    };
    initAuth0();
    // eslint-disable-next-line
  }, []);

We are currently catching the error for unverified users:

error: "unauthorized"  
error_description: "Please verify your email before logging in."

Just wondering if we should have an interim page for this status which allows a user to resend the email verification or constantly checks if the user has completed it? At what point and where would we check this?

Supporting rememberLastLogin option

Describe the problem you'd like to have solved

Hi, I'm wondering if this library will support the rememberLastLogin option from some of the other SDKs (https://auth0.com/docs/libraries/lock/v11/configuration#rememberlastlogin-boolean-) as we've lost this feature switching over to the hooks-based solution.

Describe the ideal solution

The rememberLastLogin setting is supported via the React SDK

Alternatives and current work-arounds

I've tried adding this to https://auth0.github.io/auth0-react/interfaces/withauthenticationrequiredoptions.html#loginoptions even though the option isn't listed but doesn't seem to be implemented

Additional context

isAuthenticated returning false after successful login

Hi,

Its my first time using the auth0-react SDK. I've implemented the login flow using guide, and have configured my app on Auth0 with Social Connection to LinkedIn. First login, the user is redirected to the UniversalLogin when they can login through LinkedIn, but as the user is redirected back to the application, the isAuthenticated value still remains false, and I see the POST require to oauth/token returning 401 unauthorized. On the Auth0 dashboard it also showed a successful login attempt with the user account.

I've provided the Auth0Provider with the appropriate props & values filled in of course,

    <Auth0Provider
            domain=""
            clientId=""
            redirectUri={window.location.origin}
            audience=""
            onRedirectCallback={onRedirectCallback}>

Am I missing anything?

The request header for the failing oauth/token request includes grant-type: authorization-code, with the code values from successful login request. On the Auth0 documentation, it seems that client-side applications should only be using grant-type: implicit. Could this be the issue? Is there any way to specific the request sent by the SDK to oauth/token as grant-type=implicit? Any help in how to fix this issue is greatly appreciated 🙏🏼

auth0-react and next.js

Hello there,

We have recently switched over from auth0-spa to auth0-react in our next.js/node server project. I've noticed a number of these exceptions being reported in our application insights when a user logs into the application:

ReferenceError: window is not defined

Callstack:
at Ar (/home/site/wwwroot/node_modules/@auth0/auth0-react/dist/auth0-react.cjs.js:114:43293)
at _r (/home/site/wwwroot/node_modules/@auth0/auth0-react/dist/auth0-react.cjs.js:114:39556)
at e. (/home/site/wwwroot/node_modules/@auth0/auth0-react/dist/auth0-react.cjs.js:114:59060)
at /home/site/wwwroot/node_modules/@auth0/auth0-react/dist/auth0-react.cjs.js:114:2077
at Object.next (/home/site/wwwroot/node_modules/@auth0/auth0-react/dist/auth0-react.cjs.js:114:2186)
at /home/site/wwwroot/node_modules/@auth0/auth0-react/dist/auth0-react.cjs.js:114:1118
at o (/home/site/wwwroot/node_modules/@auth0/auth0-react/dist/auth0-react.cjs.js:114:886)
at e.buildAuthorizeUrl (/home/site/wwwroot/node_modules/@auth0/auth0-react/dist/auth0-react.cjs.js:114:58874)
at e. (/home/site/wwwroot/node_modules/@auth0/auth0-react/dist/auth0-react.cjs.js:114:61293)

It's important to note that the user is not seeing any error messages in the browser console, and no errors are shown in the UI. This seems to be an issue with nextjs server side rendering.

I can provide any more details and answer more questions as needed.

isAuthenticated and user are false after successful login

Please do not report security vulnerabilities here. The Responsible Disclosure Program details the procedure for disclosing security issues.

Thank you in advance for helping us to improve this library! Please read through the template below and answer all relevant questions. Your additional work here is greatly appreciated and will help us respond as quickly as possible. For general support or usage questions, use the Auth0 Community or Auth0 Support. Finally, to avoid duplicates, please search existing Issues before submitting one here.

By submitting an Issue to this repository, you agree to the terms within the Auth0 Code of Conduct.

Describe the problem

I have setup a the Auth0 React SDK and I am running into similar issues like #82 and #93 .

After a successful login (User enters username/password, auth code flow with PKCE is successful) on the client I have the following behaviour:

  • getAccessTokenSilently returns a valid token ✅
  • both user and isAuthenticated return false 🙅

Interestingly, this is the behaviour for Chrome and FF, in Safari the login fails completely.

After reading the other issues mentioned above I have tried the following things to resolve this:

  • Check the application's 'Application type' to be 'Single Page Application' and the 'Token Endpoint Authentication Method' to be 'None'
  • Cycle both of these values to a different one and then back to the original ones.
  • Set up the Auth0Provider with or without onRedirectCallback.

None of these seem to make a difference.

What was the expected behavior?

If getAccessTokenSilently returns a valid token, I would expect that user and isAuthenticated are set correctly.

Reproduction

My setup looks like this:

// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Auth0Provider } from '@auth0/auth0-react';

// const onRedirectCallback = (appState) => {
//   let returnPath;
//   if (appState) {
//     returnPath = appState.returnTo;
//   }
//   history.replace(returnPath || window.location.pathname);
// };

ReactDOM.render(
  <Auth0Provider
    domain={auth0Config.domain}
    clientId={auth0Config.clientId}
    redirectUri={window.location.origin}
    // onRedirectCallback={onRedirectCallback}
  >
    <App />
  </Auth0Provider>,
  document.getElementById('root')
);
// loginPage.js

import React, { useEffect } from 'react';
import { useAuth0 } from '@auth0/auth0-react';
import CircularProgress from '@material-ui/core/CircularProgress';

// [...]

export const LoginPage = () => {
  const { isLoading, loginWithRedirect } = useAuth0();

  useEffect(() => {
    loginWithRedirect({ audience });
  }, []);

  return <div>{isLoading && <CircularProgress />}</div>;
};
// someOtherComponent.js

import React, { useEffect, useState } from 'react';
import { useAuth0 } from '@auth0/auth0-react';

// [...]

export const someComponent = (props) => {
  const [token, setToken] = useState();
  const { isAuthenticated, user, getAccessTokenSilently } = useAuth0();

  useEffect(() => {
    const fn = async () => {
      setToken(await getAccessTokenSilently({ audience }));
    };
    fn();
  }, []);

  return (
    <>
      User: {JSON.stringify(user)}
      {isAuthenticated ? <div>logged in</div> : <div>logged out</div>}
      token: {JSON.stringify(token)}
    </>
  );
};

Environment

  • Version of auth0-react used: 1.0.0
  • Which browsers have you tested in?: Chrome, FF, Safari
  • Which framework are you using, if applicable (Angular, React, etc): React
  • Other modules/plugins/libraries that might be involved: react-admin

Include the access token in the hook

Describe the problem you'd like to have solved

Why can't the library handle getting the access token?

Instead of using this pattern

  const { getAccessTokenSilently } = useAuth0();
  const [token, setToken] = useState<string | undefined>();
  useEffect(() => {
    (async () => {
      setToken(await getAccessTokenSilently());
    })();
  }, [getAccessTokenSilently]);

I'd like to do

  const { token } = useAuth0();

Describe the ideal solution

Remove boilerplate pattern

Unauthenticated user not being redirected to the login page when cacheLocation="localstorage"

Description

Whenever an authenticated user hits a protected route they should be redirected to the login page (as stated in guide: https://auth0.com/blog/complete-guide-to-react-user-authentication/).

However, currently I'm only seeing a blank page when trying to navigate to a protected route when not authenticated.

Reproduction

Here is a snippet from my index.tsx:

ReactDOM.render(
    <Provider store={store}>
      <Router>
        <Auth0ProviderWithHistory>
          <App />
        </Auth0ProviderWithHistory>
      </Router>
    </Provider>,
    document.getElementById('root'),
  );

Auth0ProviderWithHistory:

export const Auth0ProviderWithHistory: React.FC = ({ children }) => {
  const history = useHistory();

  const onRedirectCallback = React.useCallback(
    (appState: { returnTo?: string }) => {
      history.push(appState?.returnTo || window.location.pathname);
    },
    [history],
  );

  return (
    <Auth0Provider
      domain={window.REACT_APP_AUTH_DOMAIN}
      clientId={window.REACT_APP_CLIENT_ID}
      redirectUri={window.location.origin}
      onRedirectCallback={onRedirectCallback}
      audience={window.REACT_APP_AUTH_AUDIENCE}
      cacheLocation="localstorage"
    >
      {children}
    </Auth0Provider>
  );
};

ProtectedRoute.tsx:

export const ProtectedRoute = ({ component, ...args }: any) => {
  return <Route component={withAuthenticationRequired(component)} {...args} />;
}

And finally, my routes:

<Switch>
   <Route path="/login" render={(props) => <Login auth={auth} {...props} />} />
        <Route path="/callback" render={(props) => <Callback auth={auth} {...props} />} />
        <Route component={DefaultContent} />
</Switch>

Where DefaultContent.tsx contains the nested route snippet:

<Switch>
   <ProtectedRoute path="/curve-list" component={CurveListPage} />
   ... more protected routes
</Switch>

I should see this when I hit a protected route:

Screenshot 2020-07-28 at 11 03 44

But I see a blank page. There is an error in the console: Failed to load resource: the server responded with a status of 400 () with regards to the /authorize endpoint.

If I comment out cacheLocation="localstorage" I do get redirected to the expected login page. However since the tokens are stored in memory, a refresh means the user needs to authenticate again - which is undesirable.

make better "onRedirectCallback" example to remove code and state

By submitting an Issue to this repository, you agree to the terms within the Auth0 Code of Conduct.

Describe the problem you'd like to have solved

The code in the EXAMPLES.md shows how to define onRedirectCallback, but that has not removed any parameters from the URL, i.e. code and state.

const onRedirectCallback = (appState) => {
  // Use the router's history module to replace the url
  history.replace(appState?.returnTo || window.location.pathname);
};

// https://github.com/auth0/auth0-react/blob/f84fabfe7774f537ee2b2d42f01f74f80d79ef4e/EXAMPLES.md#1-protecting-a-route-in-a-react-router-dom-app

Auth0ProviderOptions Interface explains that by default, onRedirectCallback deletes code and state.
So I think it would be better for users if the examples code was treated in the same way.

Describe the ideal solution

history.replace can also modify url parameters. So we change code like below and work well.

const onRedirectCallback = async appState => {
  history.replace({
    pathname: appState?.returnTo || window.location.pathname,
    search: '',
  });
};

Error: Consent required while requesting getAccessTokenSilently

Hello,

I am getting the Error: Consent required while requesting getAccessTokenSilently (); this happens only on localhost/https://127.0.0.1:3000/ but on production, it's working fine ( i use AWS amplify).

On my react code this is how I request the access token inside an async function

`token = await getAccessTokenSilently({
audience,
claim,
});

Currently, my workaround is to call getAccessTokenWithPopup() if the silent request returns a promise error which would allow me to run the same code without any authentication bypassing on my dev and production.

Is there a better way to address this issue? , please do let me know.

thanks in advance!

SAML connections support

Describe the problem you'd like to have solved

Maybe there is something that is just missing from the documentation, but if you need to use this library with a SAML connection to an active directory is there some different values or some other method for specifying which connection you want to use.

My application needs to be able to handle on startup to specify which SAML provider to use for its authentication.

expose the idToken

Describe the problem you'd like to have solved

I'd like to get the Id token after I authenticate a user

Describe the ideal solution

const token = auth0.getIdToken()

Alternatives and current work-arounds

Struggling to find a way to get the id token with the universal login flow without calling the /oath/token endpoint myself.

Additional context

  "auth0-js": "^9.13.2",
  "auth0-lock": "^11.24.3",

Calling redirect with
this.props.auth0.loginWithRedirect()

I can see the /oath/token endpoint is called successfully and returns an id_token

How to authenticate for multiple audiences?

Describe the problem you'd like to have solved

I need to be able to retrieve access tokens from Auth0 for multiple audiences. Given that gatsby-browser.js wraps the Auth0Provder (which specifies the audience) around the root element, I'm not sure how this can be handled.

Describe the ideal solution

Ideally, I'd like to be able to request multiple audiences in one go but I don't think that Auth0 supports that. Alternatively, I'd like a (simple) way to request credentials for a different audience from the one used on the root element wrapper.

Alternatives and current work-arounds

No alternatives or work-arounds.

Improved redirection after Auth0 login

Please do not report security vulnerabilities here. The Responsible Disclosure Program details the procedure for disclosing security issues.

Thank you in advance for helping us to improve this library! Your attention to detail here is greatly appreciated and will help us respond as quickly as possible. For general support or usage questions, use the Auth0 Community or Auth0 Support. Finally, to avoid duplicates, please search existing Issues before submitting one here.

By submitting an Issue to this repository, you agree to the terms within the Auth0 Code of Conduct.

Describe the problem you'd like to have solved

At the moment, when a user logs in to authenticate, the web app redirects off to Auth0 where the user enters their credentials and, if successful, Auth0 redirects back to the root page of the web app and then the SDK redirects to the page the user was on when the authentication was initiated.

For my web app, using Gatsby, the redirection to the root page is not as good as the behaviour with the auth0-js SDK where a separate "page" was used to handle the callback. The reason why it isn't as good is because the whole of the root page gets rendered before the post-authentication redirect takes place. With the auth0-js SDK, the separate callback page allowed for minimal rendering to happen.

Describe the ideal solution

Provide a means to specify where Auth0 should redirect back to. Ideally, I'd like to be able to have Auth0 redirect straight back to the page the user was on but, if that isn't possible, allow for a minimal callback page to be used.

Example Gatsby app won't build

Please do not report security vulnerabilities here. The Responsible Disclosure Program details the procedure for disclosing security issues.

Thank you in advance for helping us to improve this library! Please read through the template below and answer all relevant questions. Your additional work here is greatly appreciated and will help us respond as quickly as possible. For general support or usage questions, use the Auth0 Community or Auth0 Support. Finally, to avoid duplicates, please search existing Issues before submitting one here.

By submitting an Issue to this repository, you agree to the terms within the Auth0 Code of Conduct.

Description

There are several problems with the sample code provided for use with Gatsby. This issue covers the ones I've discovered.

Reproduction

In a clean directory, clone the repo and go into auth0-react/examples/gatsby-app.

Run npm install. There will be errors because package.json has three file references instead of version references (@auth0/auth0-react, react and react-dom). Fix those and run npm install again.

Once that completes, run gatsby build. This fails in Nav.js because location is not defined. I "hacked" around that with:

const isBrowser = typeof window !== "undefined"
const pathname = isBrowser ? location.pathname : "/";

but I don't know if that is the correct solution :)

Environment

Please provide the following:

  • Version of this library used: current repo as of 7th August 2020. Last commit was caa2d09

Auth token expiration uses different setting from Auth0 compared with auth0-js SDK

Description

I have this code in my app to allow me to verify what I'm getting back from Auth0:

getAccessTokenSilently().then(token => console.log(token))

Using jwt.io to decode the displayed token shows that it expires in 24 hours. In checking the token settings, it looks like this SDK is getting the Token Expiration value whereas auth0-js got the Token Expiration for Browser Flows value:

image

I'm raising this as an issue because it is a change in behaviour between the two SDKs which was unexpected on my part.

Environment

Please provide the following:

  • Version of this library used: 1.0.0
  • Version of the platform or framework used, if applicable: Gatsby 2.24.27, React 16.12.0

Support Auth0Provider's clientId change

Please do not report security vulnerabilities here. The Responsible Disclosure Program details the procedure for disclosing security issues.

Thank you in advance for helping us to improve this library! Your attention to detail here is greatly appreciated and will help us respond as quickly as possible. For general support or usage questions, use the Auth0 Community or Auth0 Support. Finally, to avoid duplicates, please search existing Issues before submitting one here.

By submitting an Issue to this repository, you agree to the terms within the Auth0 Code of Conduct.

Describe the problem you'd like to have solved

We are using different clientId in our app for different environments (maybe we shouldn't, but we are stuck with that for a while).
Currently Auth0Provider creates the Auth0 client once with the first initial props. (https://github.com/auth0/auth0-react/blob/master/src/auth0-provider.tsx#L189-L191)
If we change later the clientId, the client wont be changed.

Auth0Provider should properly update/recreate the auth0 CLient when the clientId or (other clientOpts) change. Perhaps with a useEffect.

Alternatives and current work-arounds

Our current workaround is to pass a key prop with the clientId as key. This will cause the Auth0Provider and the auth0 client to be recreated. But the big drawback is that it unmounts all the child tree.

Calling local logout does not clear auth0 provider's state

Description

When calling logout({localOnly: true}) the cookies are removed from the browser, but the auth0 provider's state, (which is parsed down via withAuth0) still has isAuthenticated: true and all the rest of its state unchanged. This remains until page is refreshed.

Without this data being cleared (or there being some other way to manually clear this data) the ability to do a local logout seems pointless.

Reproduction

In a react project with auth0 login, once logged in, have a component which renders the auth0 user and isAuthenticated properties. Have a button which calls logout({localOnly: true}). The isAuthenticated is now falsely displaying true.

Error: "Invalid state" After successful login.

Description

As suggested here #49 (comment)) I ran the basic sample app with my domain and clientId.

My management logs show Success Login and Success Exchange. Though in the webapp I'm not logged in. Error message there is Error: Invalid state

Full Error stack:

Inline Babel script:24 Error: Invalid state
    at e.<anonymous> (auth0-spa-js.production.esm.js:15)
    at auth0-spa-js.production.esm.js:15
    at Object.next (auth0-spa-js.production.esm.js:15)
    at auth0-spa-js.production.esm.js:15
    at new Promise (<anonymous>)
    at o (auth0-spa-js.production.esm.js:15)
    at e.handleRedirectCallback (auth0-spa-js.production.esm.js:15)
    at auth0-provider.tsx:196
    at step (auth0-react.js:95)
    at Object.next (auth0-react.js:76)
App @ Inline Babel script:24
renderWithHooks @ react-dom.development.js:14938
updateFunctionComponent @ react-dom.development.js:17169
beginWork @ react-dom.development.js:18745
beginWork$1 @ react-dom.development.js:23314
performUnitOfWork @ react-dom.development.js:22289
workLoopSync @ react-dom.development.js:22265
performSyncWorkOnRoot @ react-dom.development.js:21891
(anonymous) @ react-dom.development.js:11224
unstable_runWithPriority @ react.development.js:2685
runWithPriority$1 @ react-dom.development.js:11174
flushSyncCallbackQueueImpl @ react-dom.development.js:11219
flushSyncCallbackQueue @ react-dom.development.js:11207
scheduleUpdateOnFiber @ react-dom.development.js:21334
dispatchAction @ react-dom.development.js:15795
(anonymous) @ auth0-provider.tsx:203
step @ auth0-react.js:95
(anonymous) @ auth0-react.js:76
rejected @ auth0-react.js:67
Promise.then (async)
step @ auth0-react.js:68
(anonymous) @ auth0-react.js:69
__awaiter @ auth0-react.js:65
(anonymous) @ auth0-provider.tsx:192
(anonymous) @ auth0-provider.tsx:205
commitHookEffectListMount @ react-dom.development.js:19866
commitPassiveHookEffects @ react-dom.development.js:19904
callCallback @ react-dom.development.js:182
invokeGuardedCallbackDev @ react-dom.development.js:231
invokeGuardedCallback @ react-dom.development.js:286
flushPassiveEffectsImpl @ react-dom.development.js:22988
unstable_runWithPriority @ react.development.js:2685
runWithPriority$1 @ react-dom.development.js:11174
flushPassiveEffects @ react-dom.development.js:22955
(anonymous) @ react-dom.development.js:22834
workLoop @ react.development.js:2629
flushWork @ react.development.js:2584
performWorkUntilDeadline @ react.development.js:2196

Reproduction

I changed index.html to following:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
    />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Auth0 React</title>
  </head>
  <body>
    <div id="app"></div>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
    <script src="https://unpkg.com/babel-polyfill@6/dist/polyfill.min.js"></script>
    <script
      crossorigin
      src="https://unpkg.com/react@16/umd/react.development.js"
    ></script>
    <script
      crossorigin
      src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"
    ></script>
    <script src="https://cdn.auth0.com/js/auth0-spa-js/1.7/auth0-spa-js.production.js"></script>
    <script src="auth0-react.js"></script>
    <script type="text/babel" data-presets="es2015,es2016,es2017,stage-3,react">
      const { Auth0Provider, useAuth0 } = reactAuth0;
      const { useState } = React;

      const App = () => {
        const {
          isAuthenticated,
          isLoading,
          getIdTokenClaims,
          getAccessTokenSilently,
          getAccessTokenWithPopup,
          loginWithRedirect,
          loginWithPopup,
          logout,
          error
        } = useAuth0();
        const [token, setToken] = useState(null);
        const [claims, setClaims] = useState(null);

        if (isLoading) {
          return <div>loading...</div>;
        }

        console.error(error);

        return isAuthenticated ? (
          <div>
            <button
              onClick={() => logout({ returnTo: window.location.origin })}
            >
              logout
            </button>
            <button
              onClick={async () => setToken(await getAccessTokenSilently())}
            >
              Get access token
            </button>
            <button
              onClick={async () => setToken(await getAccessTokenWithPopup())}
            >
              Get token with popup
            </button>
            <button onClick={async () => setClaims(await getIdTokenClaims())}>
              Get id_token claims
            </button>
            {token && <pre>access_token: {token}</pre>}
            {claims && (
              <pre>id_token_claims: {JSON.stringify(claims, null, 2)}</pre>
            )}
          </div>
        ) : (
          <div>
            <button onClick={() => loginWithRedirect()}>
              Login with redirect
            </button>
            <button onClick={() => loginWithPopup()}>Login with popup</button>
          </div>
        );
      };

      ReactDOM.render(
        <Auth0Provider
          domain="benchkram.eu.auth0.com"
          clientId="40CVUjHIguVHVDgjDiurIpldXqp0ySau"
          redirectUri={window.location.origin}
        >
          <App />
        </Auth0Provider>,
        document.getElementById('app')
      );
    </script>
  </body>
</html>

Allow the user to pass in a pre-existing Auth0Client

Describe the problem you'd like to have solved

I'd like to be able to easily integrate Auth0 into a client defined statically in my app (such as ApolloClient) without sacrificing the convenience and features of auth0-react.

Describe the ideal solution

The Auth0Provider component would accept a single client prop, as an alternative to the current props which act as configuration options to be passed to an internally created client instance. This client would be an Auth0Client instance created with auth0-spa-js.

I could then create my own Auth0Client, plug it into my ApolloClient instance using a link, and then provide it to the rest of my app, and I still get the nice convenience of cached authentication state and user data from auth0-react.

Alternatives and current work-arounds

  1. Re-implement features of auth0-react in my own custom React context, like the caching behavior for important information.
  2. Expose or otherwise "steal" the client which auth0-react creates using some terrible magic.

Additional context

For an analogous example of how this is done, see Okta's React library.

This is, in my opinion, the most robust and seamless way to provide higher levels of user customization to a library like this one without complicating the usage for beginners or exposing some kind of static access pattern through a ref or similar confusing method.

Ideally you could just take the client prop and toss it straight into your useState which already exists in the Auth0Provider if it's provided instead of creating your own.

Expose the auth0Client statically

Describe the problem you'd like to have solved

Right now the Provider requires all the Auth0Options defined as props. Which is fine. But ideally Id like to just give it a client potentially.

My use case is when you want React to know about auth things, but also things outside of react. Ie we use Relay, and its fetch method lives outside react, so there is no ability for me to get that accessToken without also having access to the client.

Describe the ideal solution

Being able to provide it with a client, rather than the options.

isAuthenticated is false after successful login

After following the SPA setup guide I have similar problems to #49 #60 and #63.

The fix of cycling Application type is not working for me. I have also tried to enable refresh tokens as mentioned in #60 but see the same results.

I see 'Success Login' events in my User History and see populated code fields in my callback urls. But isAuthenticated remains false.

I have tried to get the CRA example app found in this repo running with my app credentials but am struggling to get the npm dependencies installed correctly to the point where the example app will start.

Any further troubleshooting ideas? Should I try the older client JS library?

TypeScript isn't compiled for release

Description

Seems like you guys forgot to compile this project for release. The released package has no dist folder, just src. I don't really understand how other people aren't flagging this.

Getting sameSite cookie warning from auth0.is.authenticated

Description

Firefox console reports that
"Cookie “auth0.is.authenticated” will be soon rejected because it has the “sameSite” attribute set to “none” or an invalid value, without the “secure” attribute.
Checking node_modules/@auth0/auth0-spa-js/src/storage.ts shows that the cookie is being created with secure: true, sameSite: 'none', as well as the actual cookie: set-cookie: auth0=... Path=/; Expires=Mon, 10 Aug 2020 23:33:29 GMT; HttpOnly; Secure; SameSite=None.
This is an issue when using Brave with default settings, or if a user has crossSite cookies disabled because it doesn't save the user login session.

Reproduction

Followed the most recent React SDK blog post creating an SPA.

Environment

  • Version of this library used: "^1.0.0"
  • Other relevant versions: Arch Linux using Firefox/Brave Browsers

Something went wrong when trying to reset password?

Description

I’m using auth0-react sdk and universal login.
When the “forgot password” button is triggered.
entering a new password throws a message “Something went wrong, please try again”.
But the password does change.

Expected behavior: After successful password reset user should be redirected to the app for login.

This flow is working fine if I use "Customize Password Reset" Page.
The look is old but it properly routes the user back to the app after reset password.

Reproduction

  1. Click Forgot Password in the universal login screen
  2. Check email for reset password link
  3. Click the email link
  4. Enter new password and confirm
  5. Error Something went wrong, please try again
  6. Login with the new password still works

Environment

SDK version: 1.0.0
Browser: Chrome version 84.0.4147.89

Possible api call duplication in Auth0Provider

Description

I was looking a the code of both auth0-react and auth0-spa-js libraries and i noticed that in auth0-spa-sj in isAuthenticated method of Auth0Client getUser method is used:

  
      public async isAuthenticated() {
        const user = await this.getUser();
        return !!user;
    }
  

And in auth0-react Auth0Provider both methods are used like this:

  
      const isAuthenticated = await client.isAuthenticated();
      const user = isAuthenticated && (await client.getUser());
      dispatch({ type: 'INITIALISED', isAuthenticated, user });
  

Possible solution

It is possible to remove duplicated getUser invokation:

  
      const user = await client.getUser();
      dispatch({ type: 'INITIALISED', isAuthenticated: !!user, user });
  

Is that right or am I missing something?

Additional context

Sorry about my english.

Enable loginWithPopup to optionally accept an existing popup window

This change was recently added to allow passing in an existing popup window to loginWithPopup allowing customization of additional windowFeatures in the window.open specification.

However, Auth0Provider appears to not have been updated and does not allow passing in this new configuration.

It'd be great to get this interface updated so we can use this new feature in auth0-spa-js!

isAuthenticated is always false

Hello, I am following the 'React: Login" quickstart (https://auth0.com/docs/quickstart/spa/react/01-login#install-the-auth0-react-sdk) to implement auth0 into one of my projects. However, isAuthenticated remains false after logging in, both following the specific quickstart tutorial and when trying to utilize it elsewhere (see code snippet below).

https://github.com/ryanKrumbholz/qwik/blob/60dd026f16a91872181ce23f7a7a3c11cb1a0dc2/packages/qwik-client/qwik-client/src/components/AuthenticatedRoute/AuthenticatedRoute.tsx#L2-L10

Using v1.0.0

Password-less Support

Will the provided auth client be supporting auth.passwordLessStart methods like the web-sdk in the future?

Contributing to SDK

Hello Sir, I am looking to work on the project but I can't find issues or ROADMAP for the same. So, that I can contribute regularly. @adamjmcgrath

Login required new oAuth erro?

Hi, I’m using the auth0 React SDK and trying to make posts to a rails api that has been set up with the auth0 quickstart. When I try to post in the react front end I get a console error in Chrome like so:

Error: Login required
at new OAuthError (errors.tsx:8)
at utils.tsx:17
at utils.tsx:39
at step (0.chunk.js:210)
at Object.throw (0.chunk.js:141)
at rejected (0.chunk.js:103)

I am logged in when I get this error. Also I’m able to make posts to the api if I use the token in the test tab of the dashboard for the rails api. I’m following along with the example listed in “Call an API” at this link https://auth0.com/docs/libraries/auth0-react 1

Setting "code" query parameter breaks auth0 state

If you're logged in to my site, and then add "?code=blah" to the href, auth0 now thinks I'm not logged in. I realize this has something to do with the oauth redirect flow, but the problem is that I need to use that query parameter (stripe uses it for their oauth flow: https://stripe.com/docs/connect/collect-then-transfer-guide).

Proposed change: if code param fails to change the auth0 state, auth0-react should fall back on whatever it would have the state be if that code were excluded (instead of just saying there's no user).

user is not updated after getAccessTokenSilently({ignoreCache: true})

Describe the problem

When you refresh the access token and ignore the cache, there are potentially new claims on the user object. However, the user object is stale and there is no way to update it. auth0/auth0-spa-js#274 explains the issue and has a solution: you can call getUser() after you refresh the token. But we have no way to call getUser().

Right now, to get around this, you must hard-refresh the page.

Exposing the getUser function from the auth0-spa-js client would solve this.

What was the expected behavior?

The user object should have all the claims of the new token.

Reproduction

Create a rule in auth0 that sets a property e.g.

function (user, context, callback) {
  user.app_metadata = user.app_metadata || {};

if (user.app_metadata.mything) {
   context.idToken['https://myapp.com/mything'] = true;
   context.accessToken['https://myapp.com/mything'] = true;
}
  callback(null, user, context);
}

Periodically call getAccessTokenSilently({ignoreCache: true}) without refreshing/reloading the page. Observe the user from useAuth0(). It will not have the claim. Refreshing the page will populate the user with the claim.

Environment

Version: 1.0.0
Browsers: Chrome

How to access raw ID token?

I need to access the raw ID token after a user logs in. I don't see any way to do this with the useAuth0 hook.

Failed Silent Auth on page reload

Describe the problem

I have followed code example in The Complete Guide to React User Authentication with Auth0 and noticed the behaviour of the login state not persisting on reload. After trying this on different browsers I found it only works as expected on Firefox and Chrome.

I also raised this on stack overflow without my success: Auth0 does not persist login on page refresh for email/password

What was the expected behaviour?

When a user is logged in and opens a new tab or reloads the page, the Auth0Provider should make a silent auth call to log in the user without having to make them reloading again.

Reproduction

I used the example code from the blog post with a few changes.

AuthProvider.jsx

const AuthProvider = ({ children }) => {
  const history = useHistory()

  const onRedirectCallback = appState => {
    history.push(appState?.returnTo || window.location.pathname)
  }

  return (
    <Auth0Provider
      domain={process.env.REACT_APP_AUTH0_DOMAIN}
      clientId={process.env.REACT_APP_AUTH0_CLIENT_ID}
      redirectUri={window.location.origin}
      onRedirectCallback={onRedirectCallback}
    >
      {children}
    </Auth0Provider>
  )
}

Routes.jsx

export default function Routes() {
  const { isLoading, isAuthenticated } = useAuth0()

  const getDashboard = () => {
    //determine which dashboard to return
  }

  if (isLoading) return <p>Loading...</p>

  if (isAuthenticated) {
    return (
      <Suspense fallback={<p>loading...</p>}>
        <Switch>
          <Route exact path="/">
            {getDashboard()}
          </Route>
          <Route>
            <NotFound />
          </Route>
        </Switch>
      </Suspense>
    )
  }

  return <SignInAndRegister />
}

SignInAndRegister.jsx

export default function SignInAndRegister() {
  const { loginWithRedirect } = useAuth0()
  return (
    <div className="p-4 max-w-screen-md h-screen overflow-hidden flex items-center align-center mx-auto">
      <div className="w-full">
        <h1 className="text-xl text-center mb-6">My Website</h1>
        <PrimaryButton onClick={loginWithRedirect} fullWidth={true}>
          Login
        </PrimaryButton>
        <div className="mb-3" />
      </div>
    </div>
  )
}

Steps to reproduce the error:

  1. Run app (this app is using create-react-app), so yarn start
  2. Navigate to localhost:3000
  3. Click login (which will navigate you to the Lock UI)
  4. Sign in with username/password
  5. App is redirected back to / with ?code=<code>
  6. isAuthencated value flips to true and Dashboard component is rendered
  7. Reload the page
  8. Silent auth call fails, making the user log in again

The failed Failed Silent Auth has the information:

{
  "date": "2020-08-27T07:38:48.043Z",
  "type": "fsa",
  "description": "Login required",
  "client_id": <client_id>,
  "client_name": <client_name>,
  "ip": <ip>,
  "user_agent": "Safari 13.1.2 / Mac OS X 10.15.6",
  "details": {
    "body": {},
    "qs": {
      "client_id": <client_id>,
      "redirect_uri": "http://localhost:3000",
      "scope": "openid profile email",
      "response_type": "code",
      "response_mode": "web_message",
      "state": <state>,
      "nonce": <nonce>,
      "code_challenge": <code_challenge>,
      "code_challenge_method": "S256",
      "prompt": "none",
      "auth0Client": <auth0Client>
    },
    "connection": null,
    "error": {
      "message": "Login required",
      "oauthError": "login_required",
      "type": "oauth-authorization"
    }
  },
  "hostname": "<my-app>.auth0.com",
  "audience": "https://<my-app>.auth0.com/userinfo",
  "scope": [
    "openid",
    "profile",
    "email"
  ],
  "auth0_client": {
    "name": "auth0-react",
    "version": "1.0.0"
  },
  "log_id": <log_id> ,
  "_id": <_id>,
  "isMobile": false
}

Environment

  • "@auth0/auth0-react": "^1.0.0",
  • "react": "^16.13.1"
  • "react-scripts": "3.4.1",
  • Firefox (works), Chrome (works), Brave (fails), Safari (fails)

I have verified my app is set up with

  • Allowed Callback URLs: localhost:3000
  • Allowed Logout URLs: localhost:3000
  • Allowed Web Origins: localhost:3000
  • Refresh Token Behavior: Non-Rotating
  • Application Type: Single Page Application
  • Token Endpoint Authentication Method: None

Option to cache a token

Describe the problem you'd like to have solved

I'm using this library on my React app and to protect calls to an API. Each time I made an API call, it generates a new access token. Since the token is good for some amount of time (configurable in Auth0), I'd like an option to cache the token.

Describe the ideal solution

Ideally there would be some additional options around getting tokens in addition to the current get token silently. Perhaps getOrCreateToken or something like that which checks the cache first or fetches the token if need be.

Alternatives and current work-arounds

I'm storing the token in local storage and as a cookie (I know it's gross but some folks love cookies). I don't have a smart way to know how to replace the token in local cache.

...
  const { isLoading, isAuthenticated, user, logout, getAccessTokenSilently } = useAuth0();

  useEffect(function mountCookie() {
    async function setCookie() {
      if (isAuthenticated) {
        const token = await getAccessTokenSilently({});
        localStorage.setItem('token', token);
        let expiry = new Date();
        expiry.setHours(expiry.getHours() + 10);
        const myCookie = `awesomeCookie=${token}; expires=${expiry}; path=/`;
        window.document.cookie = myCookie;
      }
    }
    setCookie();
  }, [isAuthenticated, getAccessTokenSilently])
...

Additional context

Note 1: I tried your other library for SPA and this one is better, thank you!

Note 2: I found the behavior of the service is different if you provide an empty object to getAccessTokenSilently or if you provide scopes. If you provide an empty input you get an access token, but if you provide some scopes then you will get a JWT. I'm testing both options, the example above is with an access token only.

Support earlier version of react and react-dom

Describe the problem you'd like to have solved

Can you support an earlier version of react and react-dom? I'm using 16.11. It works fine but the warning is annoying. It's not possible to upgrade my version of react since this is in a mono-repo with an expo react-native app that requires 16.11 (latest version of expo).

Describe the ideal solution

Update these lines
https://github.com/auth0/auth0-react/blob/master/package.json#L92-L93

To

    "react": "^16.11.0",
    "react-dom": "^16.11.0",

Error: Invalid parameter: client_id must be a string

Hello,

I have been using the react-auth0-spa as per the quicks start documentation. I am trying to change over to the @auth0/auth0-react.

I have installed the rpm package and made the code modification for the switch over, but I am getting an error stating 'Error: Invalid parameter: client_id must be a string'.

Here is my piece of code

import { Auth0Provider } from '@auth0/auth0-react';
import config from './auth_config.json';

app.js

ReactDOM.render( <Auth0Provider domain={config.domain} client_id={config.clientId} redirect_uri={window.location.origin} onRedirectCallback={onRedirectCallback}> <Provider store={configureStore()}> <App /> </Provider> </Auth0Provider>, document.getElementById('root') );

config.json
{
"domain": "dev-[].auth0.com",
"clientId": "--------------------"
}

thanks in advance

Auth0Provider not sending client_id

Description

I'm using auth0/auth0-react and trying to follow Complete Guide to React User Authentication With Auth0. When I try to implement the LoginButton component and test, I get an error that the client_id is missing.

Reproduction

Steps taken are as close as possible to your tutorial with the exception that this is not a "from scratch" project. I am trying to modify ArchitectUI, a popular dashboard React template project. I am following the tutorial up to the point of creating a Login/Logout Button component and testing that the user is forwarded to Auth0 for authentication. I also made sure to configure the domain, client_id, and audience properties for the Auth0Provider component.

  • Log entry from dashboard
    {
    "date": "2020-07-14T22:55:59.867Z",
    "type": "f",
    "description": "Missing required parameter: client_id",
    "connection_id": "",
    "ip": "",
    "user_agent": "Chrome 83.0.4103 / Windows 10.0.0",
    "details": {
    "body": {},
    "qs": {
    "audience": "
    ",
    "scope": "openid profile email",
    "response_type": "code",
    "response_mode": "query",
    "state": "
    ",
    "nonce": "
    ",
    "code_challenge": "
    ",
    "code_challenge_method": "S256",
    "auth0Client": "
    "
    },
    "error": {
    "message": "Missing required parameter: client_id",
    "oauthError": "invalid_request",
    "type": "request-error"
    },
    "session_id": "****************"
    },
    "hostname": "
    ",
    "auth0_client": {
    "name": "auth0-react",
    "version": "1.0.0"
    },
    "log_id": "
    **********************",
    "_id": "**********************************************************",
    "isMobile": false
    }
  • Error
    image

Environment

  • auth0/auth0-react 1.0
  • React 16.12.0
  • react-router-dom 5.1
  • ArchitectUI React template project Project link
  • Win10, VS Code

isAuthenticated returning false for newly signed up user before email verification is done

Hello,

I recently started using @auth0/auth0-react and I am experiencing the following issue for a newly signed up user ( email confirmation pending).

  1. isAuthenticated returns false for a newly signed up user

  2. The log summary in Auth0 dashboard indicates
    Type: Failed Login
    Description: Please verify your email before logging in.

  3. The user object returned in undefined

In my App.js file, I have the following check before I return the Routes which is right now resulting in an infinite redirect loop for a newly signed up user until the email is verified/

if (!isAuthenticated) return loginWithRedirect(); return <Routes></Routes>;

The earlier implementation using react-auth0-spa.js used to return isAuthenticated=true & the user object with email_verified=false for a newly signed up user which would allow me to conditionally redirect the user to a page asking to verify his/her email address to proceed.

Another solution to this would be to block the user right at the login screen ( throw a validation error ) if the email address is not verified - is there any option in the dashboard for enabling such a behavior?

Please do help to navigate this scenario.

thanks in advance.

How to call APIs without using React hooks?

Please do not report security vulnerabilities here. The Responsible Disclosure Program details the procedure for disclosing security issues.

Thank you in advance for helping us to improve this library! Your attention to detail here is greatly appreciated and will help us respond as quickly as possible. For general support or usage questions, use the Auth0 Community or Auth0 Support. Finally, to avoid duplicates, please search existing Issues before submitting one here.

By submitting an Issue to this repository, you agree to the terms within the Auth0 Code of Conduct.

Describe the problem you'd like to have solved

When using fetch against an API that uses Auth0's credentials for authentication, this SDK takes a very different approach to, say, auth0-js.

This SDK provides a nice example of how to call an API that requires the credentials, by using React hooks. Unfortunately React hooks have many limitations on how and when they can be used. So, for example, where I have a useEffect that is triggered when the user wants to move to the next page of data, I can't call useApi there because you aren't allowed to call React hooks inside a callback.

Describe the ideal solution

Please provide additional guidance on how to interact with the SDK besides React hooks.

Alternatives and current work-arounds

At the moment, my only option would seem to be to stick with the auth0-js SDK I'm currently using but that has its own problems and limitations that I had hoped would be solved by switching to the newer SDK.

withAuthenticationRequired on Routes Leads to Blank Page After Login

Description

We've recently deployed our first Auth0-enabled React app and I used the withAuthenticationRequired method in auth-react to protect two of our routes in our primary application. When you first load the app on a computer with cache cleared (or which has never logged in before), it will follow to the login page properly and process the login properly, then dump you back to the skeleton of the site with no content in the render area. Pressing F5 will load the page as expected after that point. It never has the error again once you're logged in.

Reproduction

Our index.js calls the plugin and then renders with ReactDom and BrowserRouter statements:

import { Auth0Provider } from "@auth0/auth0-react";

ReactDOM.render(
  <Auth0Provider
    domain="REDACTED"
    clientId="REDACTED"
    redirectUri={window.location.origin}
  >
	  <BrowserRouter>
	      <App />
	      <Spinner />
	  </BrowserRouter>
  </Auth0Provider>,
  document.getElementById('root')
);

Then, the primary app's js file will route the endpoints for both primary functions of the app:

  render() {
    return (
      <div className="App">
        <header>
          <div id="logo">
            <span className="icon"></span>
            <span>REDACTED APP NAME</span>
          </div>
        </header>
        <main>
          <Switch>
            <Route exact path="/related_orders/:orderId" location={this.props.location} render={props => <OrderList {...props} sendOrderInfoToParent={this.setOrderInfo} sendCustInfoToParent={this.setCustInfo}/>}>
            </Route>
            <Route path="/calendar">
              <Calendar ordersFromParent={this.state.orders} custInfoFromParent={this.state.custInfo}/>
            </Route>
          </Switch>
        </main>
      </div>
    );
  }
}

Inside of each path, I've enclosed the export default statement with the withAuthenticationRequired statements as so:

export default withAuthenticationRequired(Calendar, {
    // Show a message while the user waits to be redirected to the login page.
    onRedirecting: () => <h2 align="center" style={{ color: 'white' }}>One moment, please.</h2>,
});

Still, each time I use a private window or clear my cache, I get the login process until it redirects back and then just sits at a skeleton page with nothing in the render zone:
Screenshot 2020-06-30 20 23 28

If I press F5, the app renders properly:
Screenshot 2020-06-30 20 25 00

Environment

We're running in a Docker image in Kubernetes, base image is node:alpine.

Relevant Plugins:
auth0-react v1.0.0
react v16.11.0
react-dom v16.13.1
react-router-dom v5.2.0

Clients Tested (Same browsers on all 4 platforms):

  • Windows 10 1909
  • Windows 10 2004
  • Mac OS X 10.15.5
  • Mac OS X 10.15.3
  • Chrome 83.0.4103.116
  • Firefox 77.0.1 (64-bit)

Package.json Dependencies:
"@auth0/auth0-react": "^1.0.0",
"@fortawesome/fontawesome-svg-core": "^1.2.28",
"@fortawesome/free-solid-svg-icons": "^5.13.0",
"@fortawesome/react-fontawesome": "^0.1.9",
"@material-ui/core": "^4.9.14",
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^7.2.1",
"axios": "^0.19.2",
"cors": "^2.8.5",
"date-fns": "^2.12.0",
"express": "^4.17.1",
"express-jwt": "^5.3.3",
"http": "0.0.1-security",
"jwks-rsa": "^1.8.1",
"logkitty": "^0.7.1",
"mobx": "^5.15.4",
"mobx-react": "^6.2.2",
"mobx-react-lite": "^2.0.7",
"popper.js": "^1.16.1",
"prop-types": "^15.7.2",
"react": "^16.11.0",
"react-bootstrap": "^1.0.1",
"react-bootstrap-table-next": "^4.0.2",
"react-bootstrap-table2-editor": "^1.4.0",
"react-calendar": "^3.1.0",
"react-dom": "^16.13.1",
"react-loader-spinner": "^3.1.14",
"react-native": "^0.62.2",
"react-promise-tracker": "^2.1.0",
"react-router-dom": "^5.2.0",
"react-scripts": "3.4.1",
"react-select": "^3.1.0",
"react-spinners-kit": "^1.9.1",
"react-table": "^7.0.4",
"react-time-picker": "^4.0.1",
"socket.io": "^2.3.0",
"time-number": "^1.1.0",
"websockets": "^0.2.0"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.