我正在编写一个 Next.js 项目,并使用 GitHub 和next-auth. 在 的示例中next-auth,有一个对 的调用useSession(),它返回两个对象:session和loading。但是,我见过的所有示例都没有实际使用该loading对象。
import React from 'react'
import {
useSession,
signin,
signout
} from 'next-auth/client'
export default () => {
const [ session, loading ] = useSession()
return <p>
{!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>
</>}
</p>
}
Run Code Online (Sandbox Code Playgroud)
问题: 的目的loading是什么,在实践中是如何使用的?
我有一个奇怪的问题,我不知道问题出在哪里。我使用next-auth库在我的Next.js应用程序中制作身份验证系统。
一切正常 - 我可以通过检查是否有google firebase提交凭据的帐户登录,session是否正确创建,但是当authorize回调初始化时,我传递google firestore正确登录后收到的数据。用户对象包含整个数据并且它被向前传递。
然后,当我想从中读取数据时session,我之前通过的一些数据丢失了。
代码:
/pages/api/auth/[...nextauth.js]
export default (req, res) =>
NextAuth(req, res, {
providers: [
Providers.Credentials({
name: 'Credentials',
credentials: {
phone: { label: "Phone number", type: "text" },
password: { label: "Password", type: "password" }
},
authorize: async (loginData) => {
const { csrfToken, phone, password } = loginData;
// checking if there is account with these credentials
let res = await …Run Code Online (Sandbox Code Playgroud) 我有一个安装了 Next-Auth 的 NextJS 前端和一个使用 Sanctum 的 Laravel 后端当我尝试使用 Next-Auth 的登录功能登录时,它给了我这个错误:
Request failed with status code 419
Run Code Online (Sandbox Code Playgroud)
419 与 CSRF 令牌有关,但我在调用登录方法之前通过调用 sainttum/csrf-cookie 路由来设置令牌
[...nextauth.js]
Request failed with status code 419
Run Code Online (Sandbox Code Playgroud)
apiClient.js
CredentialsProvider
({
name: 'Email and Password',
credentials: {
email: {label: "Email", type: "email", placeholder: "Your Email"},
password: {label: "Password", type: "Password"}
},
async authorize({email, password}, req) {
await apiClient.get("/sanctum/csrf-cookie");
const user = await apiClient.post('/customer/login', {
email: email,
password: password,
});
if (user) {
return user
} else {
return …Run Code Online (Sandbox Code Playgroud) 是否可以允许 next-auth 从 API 返回错误并从客户端传递它们?
例如,如果用户的电子邮件或密码不正确,API 将专门返回。在我们的移动应用程序上,这效果很好。尽管在网站上,我们使用的是 Next-auth。使用文档中的凭据示例,将返回值更改为对象会很棒。
import CredentialsProvider from "next-auth/providers/credentials"
providers: [
CredentialsProvider({
name: "Credentials",
credentials: {
username: { label: "Username", type: "text", placeholder: "jsmith" },
password: { label: "Password", type: "password" }
},
async authorize(credentials, req) {
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 user
} else {
// Return an object that will pass …Run Code Online (Sandbox Code Playgroud) 使用 next.js auth (next auth) 我正在创建 CredentialsProvider,尝试将其连接到 django 后端。除了刷新令牌策略之外,一切正常:获取新的访问令牌后,访问令牌和过期日期不保存。因此,下一个身份验证是在每个请求时发送刷新令牌。我不知道为什么,但在“首次创建令牌”后我无法更新令牌数据。
这是代码:
async function refreshAccessToken(token) {
console.log('UPDATE')
const refresh = await axios
.post('/token/refresh/', {
refresh: token.refreshToken
})
.catch((error) => {
console.log(error)
})
if (refresh && refresh.status === 200 && refresh.data.access) {
return {
...token,
accessToken: refresh.data.access,
expiresAt: Date.now() + 10 * 1000
}
}
return {
...token,
error: 'RefreshAccessTokenError'
}
}
export default NextAuth({
providers: [
CredentialsProvider({
id: 'credentials',
name: 'my-project',
async authorize(credentials) {
const auth = await axios
.post('/token/', {
username: …Run Code Online (Sandbox Code Playgroud) 我正在使用 Next Auth 并运行一个独立的 Node.js API。我正在使用使用凭证的 Next Auth 并使用 axios 将用户名和密码发送到 API。
在 API 方面,如果用户名和密码正确,我将使用 express-session 设置会话并将其保存到数据库中。
如果 Next.js 中的响应状态为 201,我想将 API 中的快速会话令牌添加到我的 Next.js 会话中。
下面的代码正在工作,我进行身份验证,当我在受保护的页面中进行 console.log 会话时,我看到在服务器上设置的快速会话令牌。该令牌也存储在 mongoDB 中。但这是正确的吗?这样做的目的只是为了保护前端的路由,即:检查 Next.js 中是否有会话
如果在受保护的页面上我需要发出 API 请求,我是否会根据登录用户的数据库令牌检查该会话令牌?
最后,JWT 在这里适合什么,这是 Next.js 使用 JWT 处理客户端身份验证会话的方式吗?
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import axios from "axios";
export default NextAuth({
session: {
jwt: true,
maxAge: 30 * 24 * 60 * 60,
},
providers: [
CredentialsProvider({
async authorize(credentials) {
try {
const response = …Run Code Online (Sandbox Code Playgroud) 我正在尝试在 Next.js 上开发一个灵活的身份验证系统,可以使用 Spring (Java) API 后端。使用 Postman 可以完美地实现端点功能。该 API 还提供了自己的 JWT。我想使用 API 端点登录注册用户。这也意味着我需要一种方法来使用服务器中的 JWT 来对尝试登录的用户进行身份验证。
遵循 Next_auth 和 iron-sessions 的文档非常令人困惑。API 工作正常。尤其是 Next_auth 似乎为这种类型的身份验证提供了有限的支持。
我研究了很多帖子、教程,甚至发布了这个问题。这个问题最接近我想要理解的问题,但它涉及登录后状态,并且该过程看起来有点令人困惑。这个问题似乎表明在 Next 上执行自定义身份验证非常复杂,并且最好使用框架。
我是否在这里遗漏了一些东西,或者让 Next js 与外部 API 和 JWT 一起使用是否非常复杂?我不需要 Next 提供的完整堆栈功能。我也不想被迫通过 Google、Twitter、FB 等进行身份验证。
我需要这样的东西,它是使用 React 创建的,并使用 REST API 端点来登录注册用户并管理相应的用户会话。
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
var urlencoded = new URLSearchParams();
urlencoded.append("username", enteredEmail);
urlencoded.append("password", enteredPassword);
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: urlencoded,
redirect: 'follow' …Run Code Online (Sandbox Code Playgroud) 我Nextjs通过 AWS Amplify 部署了一个 (v13) 应用程序并使用NextAuth(v4.17.0)。我正在使用CredentialsProvider自定义服务器。在开发环境中一切都很好,但在生产中,session即使在数据库中创建了令牌,回调也不会触发并且会话为空
/page/api/auth/[...nextauth].tsx 忽略控制台日志哈哈
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import jwt_decode from "jwt-decode";
import { TokenInfo } from "../../../components/types/auth_types";
async function refreshAccessToken(token) {
try {
console.log("BUT WHY?");
const res = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/api/token/refresh/`,
{
method: "POST",
body: JSON.stringify({refresh: token.refreshToken}),
headers: {"Content-Type": "application/json"},
}
);
if (!res.ok) throw "refreshError";
const responseJson = await res.json();
return {
...token,
accessToken: responseJson.access,
}
} catch(error) {
return {
...token, …Run Code Online (Sandbox Code Playgroud) 我正在使用next-auth@4.22.1withnext@13.4.7和 Typescript。每当我使用该signIn()函数时,它都会像平常一样进行登录,但随后会将以下行打印到服务器的控制台:API 处理程序不应返回值,收到的对象。执行此操作后我未登录。
我检查了我的[...nextauth].ts文件,没有发现任何错误。代码如下:
import clientPromise from "@/lib/mongodbadapter";
import { MongoDBAdapter } from "@next-auth/mongodb-adapter";
import NextAuth, { AuthOptions } from "next-auth"
import DiscordProvider from "next-auth/providers/discord";
import GitHubProvider from "next-auth/providers/github";
export const authOptions: AuthOptions = {
adapter: MongoDBAdapter(clientPromise),
providers: [
DiscordProvider({
clientId: process.env.DISCORD_CLIENT_ID!,
clientSecret: process.env.DISCORD_CLIENT_SECRET!
}),
GitHubProvider({
clientId: process.env.GITHUB_CLIENT_ID!,
clientSecret: process.env.GITHUB_CLIENT_SECRET!
})
]
}
export default NextAuth(authOptions)
Run Code Online (Sandbox Code Playgroud)
我已将所有 HTML 元素包装在 SessionProvider 中,如下所示:
export default function App({ Component, pageProps: { session, ...pageProps } }: …Run Code Online (Sandbox Code Playgroud) 我需要访问 Next-Auth/Nextjs 13.4 API 路由中的用户会话数据。我已经配置了 JWT 和 Session 回调;但是,我在回调函数中指定的用户数据不会转换为 getServerSession 在 API 路由中拉取的数据。但是,使用 useSession() 时,会话数据确实正确反映在客户端页面中,因此我不确定问题是什么。
[...nextauth]/route.js
import { connectToDB } from "@/app/server/db";
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import bcrypt from 'bcrypt';
// Authorize function
async function authorize(credentials) {
const { email, password } = credentials;
const { db } = await connectToDB("Tenants");
const user = await db.collection("Users").findOne({ email });
if (user) {
const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) { return null; }
await db.collection("Users").updateOne({ email …Run Code Online (Sandbox Code Playgroud) next-auth ×10
next.js ×10
javascript ×4
reactjs ×3
api ×1
aws-amplify ×1
csrf-token ×1
laravel ×1
next.js13 ×1
node.js ×1
spring-boot ×1
typescript ×1