Giter Site home page Giter Site logo

auth0-samples / auth0-react-samples Goto Github PK

View Code? Open in Web Editor NEW
915.0 43.0 1.3K 5.54 MB

Auth0 Integration Samples for React Applications

Home Page: https://auth0.com/docs/quickstart/spa/react

License: MIT License

HTML 5.79% CSS 2.56% JavaScript 88.69% PowerShell 0.32% Shell 0.42% Dockerfile 2.22%
quickstart auth0 authentication react spa dx-sdk-quickstart

auth0-react-samples's Introduction

Auth0 React Samples

CircleCI

This is the sample code for the Auth0 React Quickstart using auth0-react.

Please check out the sample application for an example of how to integrate the Auth0 React SDK into your React applications.

What is Auth0?

Auth0 helps you to:

  • Add authentication with multiple sources, either social identity providers such as Google, Facebook, Microsoft Account, LinkedIn, GitHub, Twitter, Box, Salesforce (amongst others), or enterprise identity systems like Windows Azure AD, Google Apps, Active Directory, ADFS, or any SAML Identity Provider.
  • Add authentication through more traditional username/password databases.
  • Add support for linking different user accounts with the same user.
  • Support for generating signed JSON Web Tokens to call your APIs and flow the user identity securely.
  • Analytics of how, when, and where users are logging in.
  • Pull data from other sources and add it to the user profile through JavaScript rules.

Create a Free Auth0 Account

  1. Go to Auth0 and click Sign Up.
  2. Use Google, GitHub, or Microsoft Account to login.

Issue Reporting

If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.

Author

Auth0

License

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

auth0-react-samples's People

Contributors

aaguiarz avatar adamjmcgrath avatar albertoperdomo avatar alexisluque avatar benlizar avatar chenkie avatar davidpatrick avatar dependabot[bot] avatar evansims avatar ewanharris avatar frederikprijck avatar jmangelo avatar joshcanhelp avatar kjkurtz avatar kurtzilla avatar lbalmaceda avatar luisrudge avatar lukeocodes avatar moshfeu avatar paulioceano avatar peterblazejewicz avatar rafanog avatar saltukalakus avatar snyk-bot avatar stevehobbsdev avatar thameera avatar twistedstream avatar tylerzey avatar vmartynets avatar widcket 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

auth0-react-samples's Issues

04-Authorization errors with Authorization Extension

Going through the motions of 04-Authorization and receiving the following when trying to log in:

screen shot 2017-06-29 at 11 47 45 am

Error: invalid_token. Check the console for further details.

Console:
Object {error: "invalid_token", errorDescription: "Algorithm HS256 is not supported. (Expected algs: [RS256])"}

This came about from changing the app's client type from Single Page Application to Regular Web Application to accommodate the inclusion of the Authorization Extension.

Is there a workaround to this? I would like to start investigating using the Auth Extension, but can't find where to change the hashing algorithm.

04-Authorization examples and direction

Wondering if there may be a screencast or similar to demonstrate the implementation of 04-Authorization?

The provided code shows how to include the scope for writing messages for all users who login via auth0. But what are some recommended ways to limit grant/allow privileges based on the actual user?

I think there would would be a way to setup a rule that inspects a users login info and assigns scopes per the login (based on email or username), but am afraid that this may eventually prove unwieldy, so is there a method where I could add a scope programmatically to the token after it has been issued? Perhaps by setting up some sort of API call?

App login does not work

Hello, on 01-Login, once I click on the box with my e-mail on it an alert pops up: Error: unauthorized. Check the console for further details.

Th console says:
{error: "unauthorized", errorDescription: "Access denied.", state: "Sors.s5acNIdz7F~ofiIwORC6EbSMbMI"}

Preceeded by
Warning: setState(...): Cannot update during an existing state transition (such as within render or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to componentWillMount.

However, when I go on to the dashboard on the website, it shows that I have successfully logged in 'a few seconds ago'

So I'm not sure why the app is not showing me as logged in?

Embeddes Login example does not work; returns 403

Hi guys,

I was just trying to get the auth0-lock to work within my react application but have failed to do so (btw. I'm only trying to use the lock-widget since using the hosted login pages does currently not work with Safari/Safari mobile, but that's a different topic.)

Steps to reproduce:

Clone the repo with the Embedded Login Code.
Install the dependencies.
Create a new Client in the auth0 dashboard (since you didn't specify I used a "Single Page App Client").
Copy the client-id and the domain into "auth0-variables.js".
Start the application with "yarn start".
Click on Login and enter credentials with a user that was added manually via dashboard.
An error will be returned: POST https://YOUR_DOMAIN/oauth/token 403 ()

I really need to get this to work. Did anybody else get this to work? If not, is there any direction someone could point me to for a setup with auth0 where Safari will be supported?

EDIT: It seems that passing the option "oidcConformant: true" to the Auth0Lock is the problem. If I leave that out (and thereby also have to leave out the audience) I can successfully authenticate. I will go with that for now.

Invalid = token in class

running the current Auth.js gives me the following error when not using this whole project based on create-react-app.

`ERROR in ./app/Auth/Auth.js
Module build failed: SyntaxError: C:/Users/carlos.valencia/Documents/POCs/cux-tester-app/app/Auth/Auth.js: Unexpected token (4:11)

2 |
3 | export default class Auth {

4 | auth0 = new auth0.WebAuth({
| ^
5 | domain: ...`

As far as i know that is not valid ES2015 syntax, how do you get this to work?

handleAuthentication doesn't accept arguments

Trying to implement the react quickstart, granted in typescript so that may be the issue, but it looks like in routes.js it is calling handleAuthentication with an argument:

auth.handleAuthentication(nextState.location.hash);

but in Auth.js there is no argument. It looks like maybe err, authResult should be passed in and then forward to parseHash. Is this correct?

outdated dependencies

(AUTH-3899)
samples using outdated version of dependencies such as react-router, auth0-lock.

Where is the "authFetch" ?

Hi, I cannot find the function "authFetch" in adminPing() and cause error everything I try to ping in admin panel. Is there anything wrong or do I miss something ?

03-Calling-an-AP: Request failed with status code 401

I configured both auth0-variables.js and .env
I'm getting above error when making private api call

Insufficient scope

it works however, if I change this line in server

const checkScopes = jwtAuthz(['profile']);
//read:messages - doesnt work

Where is the logic to check if a user already exists or not?

I need to hook into the authentication process but I am not sure where. Basically, the lock will not let you signup an account that already exists. Where is this happening in the code?

I need to also create a new user in the database whenever auth creates a new user, and then simply proceed with the authentication process as normal if it is not a new user.

Is there a hook in the process that allows the Auth process to create a new auth account, or simply log someone in?

None of the info I am logging in the handleAuthentication function seems to be relevant:

  handleAuthentication() {
    this.auth0.parseHash((err, authResult) => {
      console.log(err)
      console.log(authResult)
      if (authResult && authResult.accessToken && authResult.idToken) {
        this.setSession(authResult);
        history.replace('/home');
      } else if (err) {
        history.replace('/home');
        console.log(err);
        alert(`Error: ${err.error}. Check the console for further details.`);
      }
    });
  }

After multiple login attemps, an error show without a message.

After multiple login attemps, an error show without a message.

In the console, the error show:

client.js:800 POST https://paulimar-techaid4.au.auth0.com/usernamepassword/login net::ERR_NETWORK_CHANGED
c._end @ client.js:800
c.end @ client.js:706
i.end @ request-builder.js:58
r.login @ username-password.js:37
r.loginWithCredentials @ redirect.js:66
login @ login?client=7N9Ho9OzTHNGEGsclUBWCW7IJxeUPq0r&protocol=oauth2&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fcallback&response_type=token id_token&scope=openid&audience=https%3A%2F%2Fpaulimar-techaid4.au.auth0.com%2Fuserinfo&nonce=aKTYnDk6kjg7Ct69QVyddRvAy~_5VIIP&auth0Client=eyJuYW1lIjoiYXV0aDAuanMiLCJ2ZXJzaW9uIjoiOC4xMS4zIn0%3D&state=L9pX6--2bLaWxm6P7I31KUbHklLr6Fg6:126

capture-for-jira-screenshot-20171116-164516-082

Error in the first login, after download and execute sample

When trying to login for the first time an error occur:
{error: "invalid_token", errorDescription: "Request has been terminated↵Possible causes: the n…ol-Allow-Origin, the page is being unloaded, etc."}
After reload the page and try to login again, the error is not shown anymore.

Calling Facebook GrapgQl API

How can I improve this app to call FB api from this app. I tried to call /v2/user/{user-I’d} unable to get identities.it would be really helpful if you get some working samples

Demo 03 - Calling an API throws an error

I've followed the directions for 03 - Calling an API, and I'm receiving this response when calling the private API (http://localhost:3001/api/private) on my local machine:

API Request (port 3001): GET /api/private 500 27.979 ms - 250 Error: getaddrinfo ENOTFOUND https https:443 at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:26)

This error infers that it's looking for https, but everything is configured to http as outlined in the instructions.

Can you confirm the demo works fine for you?

01-Embedded-Login: Invalid Token after login

After clicking login and authorise the app to access my details the following error shows up in the browser concole.

Object {error: "invalid_token", errorDescription: "Algorithm HS256 is not supported. (Expected algs: [RS256])"}

Browser: Chrome
Connection: Google
NodeJS: 8

Dynamically refreshing the login state

In the Lock examples, the page is refreshed once the user logs in because of the route change. But how could you achieve the same result without changing the route, i.e. by changing the state of the parent React component?

Can't resolve 'history/createBrowserHistory'

Hi. When trying to run th 01-Login example I had issues with the history.js file. The error received was:

Can't resolve 'history/createBrowserHistory'

To solve that, I had to add the history dependency to my package.json dependencies: "history": "^4.6.3"

I don't know whether this dependency was supposed to be installed as a automatic dependency of Router4 or if this is was a bug. Any thoughts?

Grant type 'http://auth0.com/oauth/grant-type/password-realm' not allowed for the client.

Hi,
When I try and login using the embedded login, I get the following error: Grant type 'http://auth0.com/oauth/grant-type/password-realm' not allowed for the client.
If I enable the password grant type in my application it works. However I can then disable cross-origin authentication and everything continues to work fine.
Is this an issue with Auth0.js V8 that the upcoming V9 should fix?
Any guidance is much appreciated.

Thanks

Questions regarding 03 - Calling-an-API

I am running into some problems running the example and not sure if I am setting them up correctly.

Firstly, I am not sure what to use for the AUTH0_AUDIENCE variable - I am using the value listed in my Api tab and am not sure if this is correct
screen shot 2017-06-16 at 12 32 33 pm

However, I am able to login, view my profile and ping the public endpoint.

It is when I try to call the private endpoint that I receive the message that I am 'unauthorized'

Could you provide any assistance on what I may be doing wrong?

Thank you!

[Best practice] Access auth in nested component.

Which would be the best practice to access the auth instance in a nested component?

Right now in the demo we pass the auth instance to the different pages as a property. I'd like to access the same instance of auth in a nested component and propagating the auth property down the tree doesn't seem right.

Would it be OK to instance the auth element in the Auth.js class, do you have a better approach or would it be some kind of anti-pattern?

// in Auth.js

// singleton pattern
export let auth = new Auth();

vs

// current export
export default class Auth

Thanks!

Empty fields not properly handle with Lock

When Signing up and login, if you left the password field blank, doesn't tell you any error.

During Sign Up, if you type a password and then errase it, the error message shown doesn't have the same style that the "can't be blank" messages shown in other fields.

capture-for-jira-screenshot-20171117-113656-770
capture-for-jira-screenshot-20171117-114120-422

Why subclass EventEmitter?

It's not clear to me from the code in Auth.js that it's using the subclassing of EventEmitter -- could it be that's not needed anymore? If so, happy to provide a PR to remove it and the dependency.

forceRefresh - Why?

In all the examples, you set the createHistory options to the following:

export default createHistory({
  forceRefresh: true
})

This causes a full page refresh after every route change, if I have understood the documentation for history correctly. So why is this the "sample" way?

Switching accounts

Apologies if this is not the forum for support questions. I am trying to 1) log into a user account, 2) log out, 3) log in with a different user account.

Step 1 and 2 work as expected, but when I click "log in" again, I am simply logged into the same account from step 1. I do not see the login form where I would be able to enter credentials for a different account.

Is this expected behavior? How can I prompt the login form to show if there is no current active session?

Thanks.

Cannot login

I received this error after login:

"You may have pressed the back button, refreshed during login, opened too many login dialogs, or there is some issue with cookies, since we couldn't find your session. Try logging in again from the application and if the problem persists please contact the administrator."

I cleaned all the browser data including cookies, but cannot get round the error, I use chrome btw, and I have the following set in the allowed callback urls section:
http://localhost:3000,http://localhost:3000/callback

did I miss something? Please help, thanks a lot!

screen shot 2017-09-08 at 8 58 14 am

outdated dependencies

(AUTH-3829)
There are some outdated dependencies:

  • auth0-js 8.1.3 -> 8.3.0
  • react-scripts 0.8.5 -> 0.9.3
  • auth0-lock 10.11 -> 10.12

Auto silent auth with no static variables?

What do you think about using window.location.origin instead of static URL?

    <script>
        parent.postMessage({
          hash: window.location.hash,
          type: 'auth0:silent-authentication'
        }, window.location.origin);
    </script>

Unsure if this presents any security issues is all 🔒

When click "Renewal Token" get an error.

In the 05-renewal-token sample, After I try to get a new token, the console show me a 403 error:

This error is due to a client missmatch. The user has to add http://localhost:3001/silent to the Allowed Callback URL, but the README file doesn't tell this.

After a while, the browser show a message about a timeout error.

Access Denied

Hi, I get Access denied; errorDescription: "Cannot read property 'split' of undefined" when I click on facebook login on the lock. Any idea for this error?

Custom Login Form update?

Is it possible we can get an update to custom login branch?

I am testing the branch directly on my localhost with my Auth0 creds. The only thing that works is signin/signout.

On signups i get Request to Webtask got ESOCKETTIMEDOUT(Error: Unsuccessful HTTP response)

and on social media login i get Error: invalid_request. Check the console for further details. but there is nothing on the console.

I think it is broken and needs to be updated.

Thanks.

Synchronous parsehash

I am using React and trying to use the auth0.parseHash method in combination with the React-router. My problem is that this method is asynchronous and works by callback. The react router cannot handle promises or that kind of callback as far as I could see. Which mean that I am having issues to use the usual <Redirect> component to redirect the user depending on the result of the hash extraction...

Considering that this is not calling any outside resource but simple reading the hash why is it a method with callback instead of a synchronous method ? Is there a way I missed to make this work with the Router ? Beside manually forcing a redirect one the processing is finished ? That process is very quick and I don't see why it should be treated as asynchronous. Maybe I am just missing something in the React or Oauth philosophy/process ?

Logout not working properly.

logout() {
// Clear access token and ID token from local storage
localStorage.removeItem('access_token');
localStorage.removeItem('id_token');
localStorage.removeItem('expires_at');
// navigate to the home route
history.replace('/home');
}

To work properly, this method should call the auth0.logout:

this.auth0.logout({
    returnTo: URL,
    client_id: AUTH_CONFIG.clientId
});

Thanks.

03-Calling-an-API. Errors with Call Private button. and 04-Authorization browser console Error

Hello.

I made a free account in auth0. I created a Client. 01 and 02 had no issues, but 03 and 04 does.

Call Private button onClick, I have output: Unauthorized

in terminal I have Error:

API Request (port 3001): GET /api/public 200 3.275 ms - 91
API Request (port 3001): GET /api/private 401 6.557 ms - 569
UnauthorizedError: jwt malformed
    at /Users/justfly/projects/auth0-react-samples/03-Calling-an-API/node_modules/express-jwt/lib/index.js:102:22
    at /Users/justfly/projects/auth0-react-samples/03-Calling-an-API/node_modules/jsonwebtoken/verify.js:27:18
    at _combinedTickCallback (internal/process/next_tick.js:95:7)
    at process._tickCallback (internal/process/next_tick.js:161:9)
API Request (port 3001): GET /api/public 304 0.946 ms - -
API Request (port 3001): GET /api/private 401 0.758 ms - 569

04 also doesn't want to run with Error in browser console:

Uncaught TypeError: Cannot read property 'split' of null
    at Auth.userHasScopes (bundle.js:58757)
    at App.render (bundle.js:37538)
    at bundle.js:27331
    at measureLifeCyclePerf (bundle.js:26611)
    at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (bundle.js:27330)
    at ReactCompositeComponentWrapper._renderValidatedComponent (bundle.js:27357)
    at ReactCompositeComponentWrapper.performInitialMount (bundle.js:26897)
    at ReactCompositeComponentWrapper.mountComponent (bundle.js:26793)
    at Object.mountComponent (bundle.js:14796)
    at ReactCompositeComponentWrapper.performInitialMount (bundle.js:26906)

PS Node 8.1.2, npm 5.0.4

Warning during npm install in React SPA sample project

After doing npm install, I got multiple warnings about skipping optional dependency.

The 2 "optional dependency" warning is shown in every sample project.

The additional warnings:

npm WARN registry Unexpected warning for https://registry.npmjs.org/: Miscellane
ous Warning EAI_AGAIN: request to https://registry.npmjs.org/react-scripts faile
d, reason: getaddrinfo EAI_AGAIN registry.npmjs.org:443

npm WARN registry Using stale package data from https://registry.npmjs.org/ due
to a request error during revalidation.

Happens intermitently in all sample projects

errorinstall2
image

02 - Custom Login Form Handle Authentication

Hello,

I've been trying out the demo under the embedded-login branch but it doesn't appear to authenticate the user when logging in with Google for example.

After debugging I noticed handleAuthentication doesn't get called when logging in - its not part of the constructor in Auth.js.

In comparison to the 01 - Embedded-Login example it is present in the constructor.

When I add it in it works as expected. Could we add it in as part of the repo?

this.handleAuthentication();

Unless I'm miss-understanding something and there is another issue here?

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.