Next 14引入Auth.js实现GitHub OAuth2.0登录

本文皆为个人原创,请尊重创作,未经许可不得转载。

前言

之前写了一篇有关Next和Auth.js的文章《Next.js 14 引入NextAuth.js,实现登录认证用户信息获取》,阐述了如何在Next 14 中引入Auth并配置,感兴趣的朋友可以点击跳转

本篇文章提到的项目已上传GitHub托管,感兴趣可点个Star~

OAuth

OAUTH协议为用户资源的授权提供了一个安全的、开放而又简易的标准。与以往的授权方式不同之处是OAUTH的授权不会使第三方触及到用户的账号信息(如用户名与密码),即第三方无需使用用户的用户名与密码就可以申请获得该用户资源的授权,因此OAUTH是安全的。oAuth是Open Authorization的简写。

Auth.js支持的Oauth集成方式

Auth.js预配置了超过80个Providers,不断进行测试的、流行的有20多种,其中包括今天需要引入到项目的GitHub登录。

开始

引入GitHub Providers

打开项目中auth.js文件,在providers中添加GitHub

添加环境变量

在app同级目录下.env文件中加入如下内容

在GitHub中注册OAuth app信息

打开你的GitHub页面,进入setting -> Developer Settings,点击New OAuth App创建此项目的OAuth信息。

添加GitHub Oauth信息,注意Authorization callback URL项。

Auth.js官方文档原文提到The default callback URL should generally take the form of [origin]/api/auth/callback/[provider], however, the default is slightly different depending on which framework you're using.

简要意思就是需要设置 [origin] [provider] 两个地方, [provider] 在此处是github ,而我们的 [origin] 对应的就是我们的项目地址[http://localhost:3000/]

点击Register application,得到Client ID,再手动生成一个Client secrets,回填到我们项目.env文件中AUTH_GITHUB_IDAUTH_GITHUB_SECRET

编写Github登录

登录方法

lib/action.ts下编写新的Oauth Provider登录方法,传输Provider id到我们auth.ts中的signIn方法中调用对应的OAuth登录逻辑(Auth.js已经写好对应的逻辑)

action.ts 复制代码
export async function SignWithProvider( pervState: LoginState | undefined,
  formData: FormData): Promise<LoginState>  {
  const providerData : any | null = formData.get('provider');
  const provider : LiteralUnion<string> = providerData ?  providerData as string : ''
  console.log('debug issues-02:',provider);
  const result = await signIn(provider)
  console.log('debug issues-03:',result);
  return {
    success: true,
    errorMsg: null
  }
}

创建一个通用的Providers按钮

接收页面组件传来的动态传给SignWithProvider方法,创建common/SignInButton.tsx文件

SignInButton.tsx 复制代码
'use client'
import { useFormState,useFormStatus } from 'react-dom';
import { SignWithProvider } from '../lib/action';
const initState = {
  errorMsg: "",
  success: false
};

export default function ProviderSignInButton({provider} : {provider?: string}) {
  const [state, dispatch] = useFormState(SignWithProvider, initState);
  const { pending } = useFormStatus();
  return (
    <>
    <form action={dispatch}
    >
      <input name='provider' style={{display:'none'}} defaultValue={provider}></input>
      {state?.errorMsg && <p> {state.errorMsg} </p>}
      <button type="submit" aria-disabled={pending}>Sign With {provider}</button>
    </form>
   </>
  )
    
};

登录页面加入github登录按钮

在之前的login/page.tsx登录页面中加入刚刚写好的Provider登录按钮。

编写GitHub回调页面

如果你刚刚留意到GitHub OAuth App配置中设置了http://localhost:3000/api/auth/callback/github/ 的回调地址,所以要对应的编写这个页面,按照路径创建api\auth\callback\github\page.tsx

page.tsx 复制代码
'use client'

import { useSearchParams } from "next/navigation"

export default function page() {
  const param = useSearchParams()
  return(
    <div style={{margin:'auto'}}>
    <p style={{padding: 30}}> this is github call back! {param.get('code')}</p>
    </div>
  )
};

编写GitHub API调用

Github登录成功回调之后,github服务端会在回调路径中回调code参数,使用code作为获取accessToken的凭证再获取到用户的信息。

由于我常常调用接口超时,所以此处不进行展示。

github登录回调返回案例:http://localhost:3000/api/auth/callback/github?code=822a62a312a71f092782

需要使用code访问: github.com/login/oauth...

获取accessToken后访问以下接口:

验证

运行项目,进入http://localhost:3000/home, 自动跳转至登录页面

点击Sign With github,需要登录授权

登录后跳转到回调页面并展示返回的code

使用code调用accessToken接口

获取用户信息

参考(Reference)

Auth.js文档: authjs.dev/guides/conf...

Github Api文档:docs.github.com/en/rest/use...

本文皆为个人原创,请尊重创作,未经许可不得转载。

相关推荐
崔庆才丨静觅1 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60612 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了2 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅2 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅2 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅3 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment3 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅3 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊3 小时前
jwt介绍
前端
爱敲代码的小鱼3 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax