七、在NextAuth.js配置OAuth的CallBack-Url

简介

获取Github的Auth2.0-Key pairs

  • 登录Github创建一个Auth2.0应用:


    image.png
  • 填写信息,点击 Register application


    image.png
  • 最后在Github上生成私钥,并且配置回调地址为:http://localhost:3001/api/auth/callback/github

将信息配置到 authnext.js

  • 修改项目根目录的 .env.local.example 为 .env.local
  • 找到,如下信息并填写对应值
GITHUB_ID=对应Client ID的值
GITHUB_SECRET=对应Client secrets的值
  • 配置 .env 的 NEXTAUTH_URL 这个默认是 http://localhost:3000 如果测试的时候换过端口什么的一定要跟着改。

配置

配置 OAuth 的回调

总结

  • 1、配置provider
  • 2、全局入口文件pages/_app.tsx要把Component放到SessionProvider的配置段下。
  • 3、前端使用Session保护,可以通过[useSession()](https://next-auth.js.org/getting-started/client#usesession)获取到Session状态,从而判断权限,例如:
import { useSession, signIn, signOut } from "next-auth/react"
export default function Component() {
  const { data: session } = useSession()
  if (session) {
    return (
      <>
        Signed in as {session.user.email} <br />
        <button onClick={() => signOut()}>Sign out</button>
      </>
    )
  }
  return (
    <>
      Not signed in <br />
      <button onClick={() => signIn()}>Sign in</button>
    </>
  )
}
import { getServerSession } from "next-auth/next"
import { authOptions } from "./auth/[...nextauth]"
export default async (req, res) => {
  const session = await getServerSession(req, res, authOptions)
  if (session) {
    res.send({
      content:
        "This is protected content. You can access this content because you are signed in.",
    })
  } else {
    res.send({
      error: "You must be signed in to view the protected content on this page.",
    })
  }
}

测试:

  • 配置后 yarn dev 运行,直接可以通过 github 进行登录登出。


    image.png

结束

  • 接下来介绍通过 Emial 完成授权登录
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容