gpt4 book ai didi

Auth0:Auth0注册后在本地数据库中创建用户

转载 作者:行者123 更新时间:2023-12-04 00:59:44 25 4
gpt4 key购买 nike

我正在使用 Auth0 来托管我所有的用户数据。我也有自己的后端,我希望有一个 Users其中的表,它将映射我的数据库生成的 userId到 Auth0 的 user_id .我在注册时在两个流程之间犹豫:

注册流程1:

  • 前端显示锁定,用户注册。
  • Auth0 重定向回前端后,前端具有 Auth0 user_id .
  • 前端在 POST /users 上调用后端(公共(public)端点)使用 user_id 创建一个新用户.
  • 在对我的后端资源服务器的每个经过身份验证的请求中,JWT 都包含 auth0 user_id ,因此数据库在 user_id 之间进行查找和我的 userId .

  • 注册流程2:
  • 前端显示锁定,用户注册。
  • 在 Auth0 上配置一个注册后 Hook ,它调用 POST /users在我的后端。此调用将生成我的数据库 userId并将其发送回 Auth0。
  • 把这个userId进入Auth0的user_metadata .
  • user_metadata将包含在 JWT 中,以便所有调用我的后端以获取资源都将包含数据库的 userId (无需额外查找)。

  • 我觉得2更扎实。是否有其他注册流程?一些 auth0 客户是否使用与我的 #2 类似的流程?我在他们的文档中没有找到太多内容。

    最佳答案

    这是我的第一篇文章,所以如果我犯了任何新手错误,请见谅。

    我发现注册流程 1 工作得很好。您没有指定您使用的是哪种技术,但这里有一个指向我的 github 的链接,在那里我有一个功能齐全的博客,使用注册流程 1 和 React、redux 和 Express 后端。

    https://github.com/iqbal125/react-redux-fullstack-blog

    我将使用这些框架进行演示,因此希望您可以针对正在使用的框架调整代码。

    我的注册流程如下:

  • 前端显示锁定用户注册
  • 用户被重定向到回调页面。
  • 然后我从回调页面重定向到“身份验证检查”页面。我在 auth-check 页面中有一个嵌套的 api 调用,它都从 auth0 获取用户数据,然后立即调用 api 端点将用户数据保存到 db。
  • api 调用检查用户是否已经在 sql db 中,然后保存用户数据,否则什么都不做。
  • 然后将用户数据保存到 redux 全局状态,并可用于在用户配置文件页面上显示数据。
  • 当用户单击注销时,将再次调用 authcheck 并从全局状态中删除用户信息,然后用户注销。
  • auth-check 然后重定向回主页。



  • 1.前端显示Lock用户注册
      login() {
    this.auth0.authorize();
    }

    2. 用户被重定向到回调页面。

    我的回调页面非常简单,我将它用作功能组件。
      <div>
    <h2>Callback</h2>
    </div>

    3. 然后我从回调页面重定向到“身份验证检查”页面

    我通过 auth.js util 组件中的 handleAuthentication() 函数执行此操作。代码从 auth0 示例中略有修改。
      handleAuthentication() {
    this.auth0.parseHash((err, authResult) => {
    if (authResult && authResult.accessToken && authResult.idToken) {
    this.setSession(authResult);
    this.getProfile();
    setTimeout( function() { history.replace('/authcheck') }, 2000);
    } else if (err) {
    history.replace('/');
    console.log(err);
    alert(`Error: ${err.error}. Check the console for further details.`);
    }
    });
    }

    你会注意到我添加了一个 getProfile() 函数
       getProfile() {
    let accessToken = this.getAccessToken();
    if(accessToken) {
    this.auth0.client.userInfo(accessToken, (err, profile) => {
    if (profile) {
    this.userProfile = { profile };
    }
    });
    }
    }

    以及 getAccessToken() 函数
      getAccessToken() {
    if (localStorage.getItem('access_token')) {
    const accessToken = localStorage.getItem('access_token')
    return accessToken
    }
    else {
    console.log("No accessToken")
    return null
    }
    }

    auth.js util 组件中的这两个函数将允许我们从 auth0 获取信息并将其保存到我们在类中声明的空对象中。
      userProfile = {}

    转到 auth-check.js 容器。我首先在构造函数中声明函数,然后是函数本身。然后我调用 componentDidMount() 生命周期方法,该方法在组件呈现时自动运行。
      constructor() {
    super()
    this.send_profile_to_db = this.send_profile_to_db.bind(this)
    }

    send_profile_to_db (profile) {
    const data = profile
    axios.post('api/post/userprofiletodb', data)
    .then(() => axios.get('api/get/userprofilefromdb', {params: {email: profile.profile.email}} )
    .then(res => this.props.db_profile_success(res.data))
    .then(history.replace('/')))
    }

    我的生命周期方法和我返回一个空的 div。
    componentDidMount() {
    if(this.props.auth.isAuthenticated()) {
    this.props.login_success()
    this.props.db_profile_success(this.props.auth.userProfile)
    this.send_profile_to_db(this.props.auth.userProfile)
    } else {
    this.props.login_failure()
    this.props.profile_failure()
    this.props.db_profile_failure()
    history.replace('/')
    }
    }

    render() {
    return (
    <div>
    </div>
    )
    }
    }

    我认为这里的代码触及了您提出的问题的核心。


    我将从 开始send_profile_to_db() 功能。

    我在这里使用 axios 发出请求。我开始对我的快速服务器进行后端 api 调用(我将在下一步中解释)并且我将用户配置文件作为数据对象参数传递给 axios。您可能想知道实际的用户配置文件数据来自哪里。

    在我的 routes.js 根组件中,我导入并初始化了一个新的 Auth 实例
    export const auth = new Auth();

    然后将其作为 Prop 传递给 AuthCheck 组件。
    <Route path="/authcheck" render={(props) => <AuthCheck auth={auth} {...props} />} />

    这允许我使用“this.props”访问 auth 类的所有属性。所以我只是使用我们在最后一步初始化的“userProfile = {}”对象,它现在包含我们的用户数据。

    在使用嵌套的“.then()”函数将数据发布到数据库后,该函数调用 axios get 请求,并将用户电子邮件作为从数据库中查找配置文件的参数。数据库配置文件包含有关用户帖子和用户评论的数据。这对于在应用程序中显示数据很有用。然后我使用另一个“.then()”语句和一个 Redux Thunk 将用户配置文件数据异步保存到全局 redux 状态。

    所以总而言之,这个 authcheck 组件做了 4 件事:

    1. 将我们从 auth0 获取的用户配置文件数据保存到我们自己的数据库中。

    2. 然后在保存数据后,立即从我们的数据库中检索相同的配置文件。

    3. 让我们的应用知道用户是否通过身份验证。

    4. 将我们的数据库用户配置文件数据保存到全局 redux 状态,以便在其他组件中使用。

    非常棒,如果你问我!


    4. api 调用检查用户是否已经在 sql db 中然后保存用户数据,否则什么都不做。

    现在这是我的服务器设置。用于用户数据库“发布”和“获取”请求。
    router.post('/api/post/userprofiletodb', (req, res, next) => {
    const values = [req.body.profile.nickname, req.body.profile.email, req.body.profile.email_verified]
    pool.query('INSERT INTO users(username, email, date_created, email_verified) VALUES($1, $2, NOW(), $3) ON CONFLICT DO NOTHING', values, (q_err, q_res) => {
    if (q_err) return next(q_err);
    console.log(q_res)
    res.json(q_res.rows);
    });
    });

    /* Retrieve user profile from db */
    router.get('/api/get/userprofilefromdb', (req, res, next) => {
    // const email = [ "%" + req.query.email + "%"]
    const email = String(req.query.email)
    pool.query("SELECT * FROM users WHERE email = $1", [ email ], (q_err, q_res) => {
    res.json(q_res.rows)
    });
    });

    需要注意的几点:

    路由器对象是 express.router()。我正在使用 psql。

    请记住添加“ON CONFLICT DO NOTHING”,否则您将保存同一用户的多个版本。

    我认为 auth0 为您提供了更多数据点,但我最终没有使用它们。

    这是我的用户表的 SQL 架构。
    CREATE TABLE users (
    uid SERIAL PRIMARY KEY,
    username VARCHAR(255) UNIQUE,
    email VARCHAR(255),
    email_verified BOOLEAN,
    date_created DATE,
    last_login DATE
    );

    5. 然后将用户数据保存到 redux 全局状态,可用于在用户配置文件页面上显示数据。

    我最终只是在第 3 步中解释了这一点。

    6. 当用户单击注销时,再次调用 authcheck 并从全局状态中删除用户信息,然后用户注销。

    见第 3 步


    7. auth-check 然后重定向回主页。

    再次看到第 3 步,哈哈。

    如果您感兴趣或者我错过了什么,请务必查看我的 repo,就像我说的那样,它是一个功能齐全的完整博客。

    关于Auth0:Auth0注册后在本地数据库中创建用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51795272/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com