【问题标题】:Next Js combined with an external REST API Authentication and atuhorizationNext Js 结合外部 REST API 身份验证和授权
【发布时间】:2021-08-24 15:56:40
【问题描述】:

我已经有一个使用 Node Js 和 express 构建的应用程序,我也有一个使用带有 redux 的 create-react-app 的前端,但现在我想将它移到下一个 Js,但我被卡住了,因为我使用我的其余完整 API 进行身份验证和授权的方式不正确,我想提一下,我的 API 已经使用 JWT 处理了这个问题(将其保存在 cookie 中)

【问题讨论】:

    标签: javascript node.js reactjs express next.js


    【解决方案1】:

    Next-Auth 在这种情况下是首选。以下示例显示了如何开始使用密码验证。

    创建一个名为/pages/api/auth/[...nextauth].js的文件

    import NextAuth from 'next-auth'
    import Providers from 'next-auth/providers'
    
    const options = {
      providers: [
        Providers.Credentials({
        // The name to display on the sign in form (e.g. 'Sign in with...')
        name: 'Email and Password',
        credentials: {
          username: { label: "Username", type: "text", placeholder: "jsmith" },
          password: {  label: "Password", type: "password" }
        },
        authorize: async (credentials) => {
          // Add logic here to look up the user from the credentials supplied eg from db or api
          const user = { id: 1, name: 'J Smith', email: 'jsmith@example.com' }
    
          if (user) {
            // Any object returned will be saved in `user` property of the JWT
            return Promise.resolve(user)
          } else {
            // If you return null or false then the credentials will be rejected
            return Promise.resolve(null)
            // You can also Reject this callback with an Error or with a URL:
            // return Promise.reject(new Error('error message')) // Redirect to error page
            // return Promise.reject('/path/to/redirect')        // Redirect to a URL
          }
        }
      }),
      ],
    }
    
    export default (req, res) => NextAuth(req, res, options)
    

    然后在你的组件代码上:

    import React from 'react'
    import {
      signIn, 
      signOut,
      useSession
    } from 'next-auth/client'
    
    export default function myComponent() {
      const [ session, loading ] = useSession()
    
      return <>
        {!session && <>
          Not signed in <br/>
          <button onClick={signIn}>Sign in</button>
        </>}
        {session && <>
          Signed in as {session.user.email} <br/>
          <button onClick={signOut}>Sign out</button>
        </>}
      </>
    }
    

    如果您分享更多您拥有的身份验证路线,我可以提供更多建议。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-12
    • 2013-04-17
    • 2012-02-10
    • 2016-01-12
    • 2020-01-26
    • 2012-09-10
    • 1970-01-01
    相关资源
    最近更新 更多