简体   繁体   中英

Auth0-js Custom Login - 401 Unauthorized

I've been working off of this React Quickstart on auth0 https://auth0.com/docs/quickstart/spa/react/02-custom-login , trying to implement a custom login. When I try to Login I get a 401 Unauthorized Error and when I try to Sign Up I get the same alert error but the user does get created and I get redirected to the home page. Mind you everything works fine using the Lock Widget but when I try to do it with the custom login it doesn't.

Here's the AuthService code which is the most relevant I feel. The Login component simply calls the login and signup methods.

export default class SocialAuthService extends EventEmitter {
  constructor(clientId, domain) {
    super()
    // Configure Auth0
    this.auth0 = new auth0.WebAuth({
      clientID: 'clientID',
      domain: 'domain',
      responseType: 'token id_token',
      redirectUri: 'http://localhost:3000/login'
    })

    this.login = this.login.bind(this)
    this.signup = this.signup.bind(this)
    this.loginWithGoogle = this.loginWithGoogle.bind(this)
    this.loginWithTwitter = this.loginWithTwitter.bind(this)
    this.loginWithFacebook = this.loginWithFacebook.bind(this)
  }

  login(username, password) {
    this.auth0.client.login({
      realm: 'Username-Password-Authentication',
      username,
      password
    }, (err, authResult) => {
      if (err) {
        alert('Error: ' + err.description)
        return
      }
      if (authResult && authResult.idToken && authResult.accessToken) {
        this.setToken(authResult.accessToken, authResult.idToken)
        browserHistory.replace('/home')
      }
    })
  }

  signup(email, password){
    this.auth0.redirect.signupAndLogin({
      connection: 'Username-Password-Authentication',
      email,
      password,
    }, function(err) {
      if (err) {
        alert('Error: ' + err.description)
      }
    })
  }

  parseHash(hash) {
    this.auth0.parseHash({ hash }, (err, authResult) => {
      if (authResult && authResult.accessToken && authResult.idToken) {
        this.setToken(authResult.accessToken, authResult.idToken)
        browserHistory.replace('/home')
        this.auth0.client.userInfo(authResult.accessToken, (error, profile) => {
          if (error) {
            console.log('Error loading the Profile', error)
          } else {
            this.setProfile(profile)
          }
        })
      } else if (authResult && authResult.error) {
        alert('Error: ' + authResult.error)
      }
    })
  }

  loggedIn() {
    // Checks if there is a saved token and it's still valid
    const token = this.getToken()
    return !!token && !isTokenExpired(token)
  }

  setToken(accessToken, idToken) {
    // Saves user access token and ID token into local storage
    localStorage.setItem('access_token', accessToken)
    localStorage.setItem('id_token', idToken)
  }

  setProfile(profile) {
    // Saves profile data to localStorage
    localStorage.setItem('profile', JSON.stringify(profile))
    // Triggers profile_updated event to update the UI
    this.emit('profile_updated', profile)
  }

  getProfile() {
    // Retrieves the profile data from localStorage
    const profile = localStorage.getItem('profile')
    return profile ? JSON.parse(localStorage.profile) : {}
  }

  getToken() {
    // Retrieves the user token from localStorage
    return localStorage.getItem('id_token')
  }

  logout() {
    // Clear user token and profile data from localStorage
    localStorage.removeItem('id_token')
    localStorage.removeItem('profile')
  }

  loginWithGoogle() {
    this.auth0.authorize({
      connection: 'google-oauth2'
    })
  }

  loginWithTwitter() {
    this.auth0.authorize({
      connection: 'twitter'
    })
  }

  loginWithFacebook() {
    this.auth0.authorize({
      connection: 'facebook'
    })
  }

}

And this is the error:

Object
code
:
"access_denied"
description
:
"Unauthorized"
original
:
Error: Unauthorized at Request.<anonymous> (http://localhost:3000/static/js/bundle.js:49311:20) at Request.Emitter.emit (http://localhost:3000/static/js/bundle.js:49954:21) at XMLHttpRequest.xhr.onreadystatechange (http://localhost:3000/static/js/bundle.js:49616:11)
statusCode
:
401
statusText
:
"Unauthorized"

Any ideas on why I'm not able to Login ?

Not sure if you got an answer, but I was running into the same problem and it was because the backend wasn't able to properly decode the JWT. Custom Login signs with a RS256 token while it seems Lock signs with HS256. You have to decode these differently in your backend.

Here's a python example

Auth0.js version 8 verifies ID tokens during authentication transactions. Only tokens which are signed with the RS256 algorithm can be verified on the client side, meaning that your Auth0 client must be configured to sign tokens with RS256. See the auth0.js migration guide for more details.

I ran into a similar issue and my fix was switching the "Application Type" setting in Auth0 from "Regular Web Application" to "Single Page Application".

The Auth0 React SDK docs make it clear that you have to register your app as a single-page application in order for Auth0 to configure the appropriate settings, so that your web client can make successful requests to their endpoints.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM