为 Next.js 应用添加授权

模板仓库: nextauthjs/next-auth-example

我进行的修改:

package.json :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
{
  "dependencies": {
    "@next-auth/upstash-redis-adapter": "^3.0.0",
    "@upstash/redis": "^1.3.1",
    "dotenv": "^16.0.0",
    "next-auth": "^4.3.3"
  },
  "devDependencies": {
    "@prisma/client": "2.16.1"
  }
}

pages/api/auth/[...nextauth].ts :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import NextAuth from 'next-auth'
import EmailProvider from 'next-auth/providers/email'
import GithubProvider from 'next-auth/providers/github'
import { UpstashRedisAdapter } from '@next-auth/upstash-redis-adapter'
import { Redis } from '@upstash/redis'

require('dotenv').config()
const redis = Redis.fromEnv()

// For more information on each option (and a full list of options) go to
// https://next-auth.js.org/configuration/options
export default NextAuth({
  // https://next-auth.js.org/configuration/providers/oauth
  adapter: UpstashRedisAdapter(redis),
  providers: [
    EmailProvider({
      server: {
        host: process.env.EMAIL_SERVER_HOST,
        port: process.env.EMAIL_SERVER_PORT,
        auth: {
          user: process.env.EMAIL_SERVER_USER,
          pass: process.env.EMAIL_SERVER_PASSWORD,
        },
      },
      from: process.env.EMAIL_FROM,
    }),
    GithubProvider({
      clientId: process.env.GITHUB_ID,
      clientSecret: process.env.GITHUB_SECRET,
    }),
    Auth0Provider({
      clientId: process.env.AUTH0_ID,
      clientSecret: process.env.AUTH0_SECRET,
      issuer: process.env.AUTH0_ISSUER,
    }),
  ],
  theme: {
    colorScheme: 'light',
  },
  callbacks: {
    async jwt({ token }) {
      token.userRole = 'admin'
      return token
    },
  },
})

.env :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
NEXTAUTH_URL=
NEXTAUTH_SECRET= # Linux: `openssl rand -hex 32` or go to https://generate-secret.now.sh/32

GITHUB_ID=
GITHUB_SECRET=

EMAIL_SERVER_USER=
EMAIL_SERVER_PASSWORD=
EMAIL_SERVER_HOST=
EMAIL_SERVER_PORT=
EMAIL_FROM=

UPSTASH_REDIS_REST_URL=
UPSTASH_REDIS_REST_TOKEN=

#需要准备

  1. 这里 新建 GitHub App,填写 Callback URL (这是你安装 App 后重定向的网址,一般是你登陆站点的首页/控制面板)并勾选 Request user authorization (OAuth) during installation ,其他根据你的需求选择。这一步获取 GITHUB_IDGITHUB_SECRET
  2. Mailgun(我使用的邮件服务)中的 Dashboard/Sending/Domain settings 下找到 SMTP credentials,点击 Add new SMTP user ,输入你想发送验证邮件的邮箱,比如 noreply@example.com ,然后得到密码。这一步获取 EMAIL_SERVER_USEREMAIL_SERVER_PASSWORDEMAIL_FROMEMAIL_SERVER_HOSTEMAIL_SERVER_PORT 可在当前新建用户页面找到;
  3. Upstash(提供 Redis 存储服务)中可得到 UPSTASH_REDIS_REST_URLUPSTASH_REDIS_REST_TOKEN

Layout of comment panels