next-auth学习使用

next-auth
nextjs的会话管理工具
依赖:next-auth
==当前页面写的是:App Router的使用方案。==
Installation
安装依赖:
npm install next-auth
写文件:app/api/auth/[…nextauth]/route.ts。
配置包含
登录Provider,可以是用户名密码以及其他登录方案
、用户登录表单信息
、验证流程
、要存进session的值
。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
47
48
49import NextAuth from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials"
const handler = NextAuth({
// 这里放next-auth的配置
providers: [
CredentialsProvider({
name: "Login", // 当前Provider的名称。区分多个Provider,在本笔记中没什么用,可以不写
//登录需要用到的参数
credentials: {
username: { label: "Username", type: "text", placeholder: "Username" },
password: { label: "Password", type: "password" }
},
async authorize(credentials, req) {
//这里模拟数据库,可以使用数据库查询
const users = [
{ id: "123", username: "admin", password: "admin" },
{ id: "2234", username: "zhangsan", password: "zhangsan" }
]
if (!credentials) return null
const lu = users.find(e => e.username === credentials.username && e.password === credentials.password)
return lu ? { id: lu.id, username: lu?.username } : null
}
})
],
callbacks: {
//对于用户信息,要先从token中取出来,然后再存储到session中。以下两个方法的token是一个实例。方法调用jwt在前,session在后。
async jwt({ token, user }) {
if (user) {
token.username = user.username
token.id = user.id
}
return token
}
async session({ session, token }) {
session.user = {
id: token.id,
username: token.username
}
return session
},
}
})
export { handler as GET, handler as POST }配置生产环境变量
1
2
3NEXTAUTH_URL=https://www.example.com/.../api/auth
# 可选。配置jwt加密密钥
NEXTAUTH_SECRET=oihi2o3g290fj3290fj90登录页面
next-auth有内置实现的登录页面,也可以自己实现登录页面。下面是自己实现的登录页面。使用signIn方法触发登录操作。
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
47
48
49
50
51
52
53
54'use client'
import { signIn, useSession } from 'next-auth/react';
// 这个方法非必须,不属于next-auth笔记,
// 将form表单数据转换为对象
function form_obj(f: HTMLFormElement) {
const obj: any = {}
const data = new FormData(f)
for (const [key, value] of data.entries()) {
obj[key] = value
}
return obj
}
//页面
export default function BlogUserLoginPage() {
//读取session的值
const session = useSession()
// 登录操作
async function login(e) {
e.preventDefault(); // 阻止表单提交
const data = form_obj(e.target)//将表单转换为对象,比如:{username:"Zhangsan",password:"zhangsan"}
alert(JSON.stringify(
//这里是登录操作
//credentials是固定值,表示使用credentials的provider
await signIn('credentials', {
redirect: false,
...data
}
)))
}
return (<>
<div>
<form onSubmit={login}>
<div>
<label htmlFor="username">Username</label>
<input type="text" id="username" name="username" />
</div>
<div>
<label htmlFor="password">Password</label>
<input type="password" id="password" name="password" />
</div>
<button type="submit">Login</button>
</form>
<div>
{session ? <div>{session.status} {session.data?.user?.name} {session.data?.user?.username}</div> : <div>w</div>}
</div>
</div>
</>
);
}
剩下的先挖坑…. 上面的应该够用了。
评论