Auth0回调URL不匹配。

25
我正在使用Auth0在React应用程序中进行LinkedIn身份验证。我已在设置中的回调URL中设置了localhost:3000/upload,期望用户在localhost:3000/login登录后将被重定向到localhost:3000/upload。然而,我总是得到这个错误:url localhost:3000/login不在回调URL列表中。为什么Auth0希望在登录后返回您刚刚登录的页面呢?难道它不应该是一些不同的URL吗?这对我来说毫无意义。
export default class AuthService {
  constructor(clientId, domain) {
    // Configure Auth0
    const options = {
      allowedConnections: ['linkedin'],
      auth: {
        params: {responseType: 'code'}
      }
    };  
    this.lock = new Auth0Lock(clientId, domain, options)
    // Add callback for lock `authenticated` event
    this.lock.on('authenticated', this._doAuthentication.bind(this))
    // binds login functions to keep this context
    this.login = this.login.bind(this)
    this.loggedIn = this.loggedIn.bind(this)
  }

  _doAuthentication(authResult){
    // Saves the user token
    console.log(authResult);
    this.setToken(authResult.idToken)
    this.lock.getProfile(authResult.idToken, (error, profile) => {
      if (error) {
        console.log('Error loading the Profile', error)
      } else {
        console.log(profile)
      }
    })
  }
//....
7个回答

19

请确保两件事情:

1). 在你的React应用程序代码中

 responseType: 'code'

2). 在Auth0仪表板中,转到“设置”->“允许的回调URL”,放置您的回调条目(localhost:3000/upload)-我认为您已经完成了,但以防万一。

输入图像描述

如果您仍然遇到问题,请告诉我。


1
嘿,谢谢你的回答。我按照你建议的做了,但它仍然将我重定向到同一个需要认证的URL。 - shangsunset
对于一个React应用程序,你应该真正使用隐式授权流...,所以在这种情况下,将responseType设置为token,并像你平常一样使用事件监听器是我的建议。有意义吗? - arcseldon
1
嘿,抱歉忘记注释了。不,它没有起作用,所以我采取了另一种方法。但是我确实使用了事件监听器。 - shangsunset
很高兴听到你解决了它 :) - arcseldon
如何允许所有客户端? - Stephan Kristyn
1
@shangsunset,你能否分享一下你的最终解决方案吗?因为我也遇到了同样的问题,希望能得到解决。 - Seer

4
在调用AuthProvider时,请确保使用与Auth0设置中相同的回调URL:
const uri='http://localhost:3000/upload';

        <Auth0Provider
        domain={domain}
        clientId={clientId}
        redirectUri={uri}>

3
请确保在将URL粘贴到Auth0设置网站时,逗号之间没有特殊的隐藏字符或空格。我没有意识到这一点,直到将每个URL放入Vim中检查并发现存在上述情况。

2
为了在成功认证后将重定向到不同的URL,您需要向Lock提供redirectUrl,如下所示:
// 配置Auth0 const options = { allowedConnections: ['linkedin'], auth: { responseType: 'code', redirectUrl: 'http://localhost:3000/upload' } }; this.lock = new Auth0Lock(clientId, domain, options)
(还要注意,responseType选项位于auth下面,而不是auth.params下面。)
如果进行重定向,您将无法到达您在登录页面中定义的事件处理程序。您需要在目标页面中添加事件处理程序(并使用responseType:token),或者在服务器代码中处理身份验证结果(如果您正在请求responseType:code,这通常是您要做的)。

0
我遇到了类似的问题“回调URL不匹配”,通过在受信任的证书上运行应用程序并使用https解决了它。
下面是Auth0应用程序设置部分关于回调URL的代码片段,其中写道:“一定要指定协议(https://),否则某些情况下回调可能会失败。”

enter image description here


1
哈哈,我也遇到过这个问题 :D - Sang Dang
你可以在没有 HTTPS 的情况下运行它。 - Matteo

0

在auth0设置中设置回调URL的原因是,任何人都可以使用您的客户端ID并向Google或LinkedIn发送请求,将响应获取到他们设置的任何地方。但是通过此设置,只有您才能访问该响应。

一旦您的应用程序被授权从LinkedIn获取数据,LinkedIn将向您指定的位置发送数据。您应该创建一个页面来处理来自LinkedIn服务器的响应。让我们将该页面命名为callback.js,这将是响应对象的示例。

accessToken: "hNuPLKTZHiE9_lnED0JIiiPNjlicRDp"
   appState: null
   expiresIn: 7200
   idToken: "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ik5FRXdSVUl5TURVeE4wSkJPRFZEUlRKRU1EVkZNemsxTXpNNU5VTXlNRGt6T0VWQlJqUkZRUSJ9.eyJodHRwOi8vbG9jYWxob3N0OjMwMDAvcm9sZSI6InNpdGVPd25lciIsImdpdmVuX25hbWUiOiJvbWFyIiwiZmFtaWx5X25hbWUiOiJpYm8iLCJuaWNrbmFtZSI6Im9tYXJpYm8xOTgyIiwibmFtZSI6Im9tYXIgaWJvIiwicGljdHVyZSI6Imh0dHBzOi8vbGg1Lmdvb2dsZXVzZXJjb250BQUFBQUkvQUFBQUFBQUFBQUEvQUNIaTNyLTEwLTEyVDIyOjU4OjAxLjgzM1oiLCJpc3MiOiJodHRwczovL3BvcnRmb2xpby15aWxtYXouYXV0aDAuY29tLyIsInN1YiI6Imdvb2dsZS1vYXV0aDJ8MTE0MDY0NTA2ODI2OTgwNTA5ODY3IiwiYXVkIjoiUEdVY242RjRRS21PRkJhb1k0UFdCeWpjVzIyT09vNGMiLCJpYXQiOjE1NzA5MjEwODIsImV4cCI6MTU3MDk1NzA4MiwiYXRfaGFzaCI6InN0R1l5SnJaMHNnbVYzSWNLWjlPeFEiLCJub25jZSI6InRrOV95b096enRmVThVVjFVMlVFR3IyMW5ORW5abjk4In0.TYS7mM8N2d7jEHFdWQGTSeAAUaDt4-0SMUG3LrcQ1r3xzY0RMGsUsEszj5xqk1GE0cIlFS10xCOYKsuHSwsFLomC1EbLjntjkledHtfD0MW84cMoXN6a-x-1-bNwl3lMYJ98qklTrNvTvkQJ6DWhei3hJ8rs8dnbNyCfckNVU6ptJU-9ef1DwWfHRomW5LQ6WSDRHZScW697gdgBEMU-Nd2SddyHhQe0kVh6lKdcbnskEAyCJLE07jfM40RQI_8LJouFcpoyImcXSDZlKv90tYfVDq9_TwE3GNaSz5I5snn0457oCgz0vuX0JoCUiaDuTIX7XiyXnozW_DxGMuhk4w"
   idTokenPayload: {http://localhost:3000/role: "siteOwner", given_name: "me", family_name: "you", nickname: "nck", name: "nm", …}
   refreshToken: null
  scope: null
   state: "xkEbffzXbdOYPLkXOUkrQeb0Jysbnlfy"
   tokenType: "Bearer"
//THIS CODE IS FOR NEXT.JS9
//auth.js
class Auth0 {
  constructor() {
    this.auth0 = new auth0.WebAuth({
      domain: "portfolio-ys.auth0.com",
      clientID: "PGUWJQKmOFBaoY4PWByjcW22OOo4c",
      redirectUri: "http://localhost:3000/callback",
      responseType: "token id_token",
      scope: "openid profile"
    });

     this.handleAuthentication = this.handleAuthentication.bind(this);
  }
     //there are too many methods are defined here i put only relevant ones
    handleAuthentication() {
        return new Promise((resolve, reject) => {
          this.auth0.parseHash((err, authResult) => {
            console.log(authResult);
            if (authResult && authResult.accessToken && authResult.idToken) {
              this.setSession(authResult);
              resolve();
            } else if (err) {
              reject(err);
            }
          });
        });
      }

setSession function is where you set the cookies based on response object. I use js-cookie package to set the cookie.

    setSession(authResult) {
        const expiresAt = JSON.stringify(
          authResult.expiresIn * 1000 + new Date().getTime()
        );
        Cookies.set("user", authResult.idTokenPayload);
        Cookies.set("jwt", authResult.idToken);
        Cookies.set("expiresAt", expiresAt);
      }


}
const auth0Client = new Auth0();
export default auth0Client;


callback.js
import React from "react" 
import auth0Client from "./auth0"
import {withRouter} from "next/router"

 class Callback extends React.Component{
    async componentDidMount(){
        await auth0Client.handleAuthentication()
        this.props.router.push('/')
    }
    render() {
        return (

                    <h1>verifying logging data</h1>

        )
    }
}

export default withRouter(Callback) //this allows us to use router

0

如果您正在使用auth0的Android(Kotlin) SDK,我注意到在运行时,请求的URL会被更改。例如:app://{your_auth0_domain}/android/{package_name}/callback://{your_auth0_domain}/android/app://{your_auth0_domain}/android//callback 原始URL为

app://{your_auth0_domain}/android/{package_name}/callback

而SDK会附加额外的部分"://{your_auth0_domain}/android/app://{your_auth0_domain}/android//callback"

解决方案:要么将与日志中显示相同的URL放入auth0设置仪表板中 或者

 WebAuthProvider
            .login(account)
            .withScheme("app") // instead of complete URL, put only the remaining part from the URL,
            .start(this, object : Callback<Credentials, AuthenticationException> {}

我希望它会对安卓/应用程序开发者有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接