使用Google API获取Google Drive全部文件夹数据问题求助
解决Google Drive API仅能获取自有上传文件夹的问题
问题核心在于授权权限范围限制:你当前使用的https://www.googleapis.com/auth/drive.file权限仅允许访问通过你的应用上传/创建的文件,无法读取Drive中已存在的其他文件夹。
修复步骤:
调整Google Provider的授权范围
将NextAuth配置中的scope替换为更宽泛的权限,遵循最小权限原则选择:- 仅需读取所有文件夹:
https://www.googleapis.com/auth/drive.readonly(推荐) - 需要读写权限:
https://www.googleapis.com/auth/drive
修改后的认证代码:
import NextAuth from "next-auth/next" import GoogleProvider from "next-auth/providers/google" export const authOptions = ({ providers: [ GoogleProvider({ clientId : process.env.GOOGLE_CLIENT_ID ?? "" , clientSecret : process.env.GOOGLE_CLIENT_SECRET ?? "", authorization: { params: { scope: "openid email profile https://www.googleapis.com/auth/drive.readonly" } }, }) ], callbacks: { async jwt({token, user , account} : any){ if (account) { token.accessToken = account.access_token; } return token }, async session({ session, token } : any) { const newSession = { ...session, accessToken: token.accessToken, }; return newSession; }, } }) const handler = NextAuth(authOptions) export {handler as GET, handler as POST}- 仅需读取所有文件夹:
强制用户重新授权
用户之前已使用旧权限完成授权,需让用户退出登录后重新登录,才能获取带有新权限的access token。优化API请求(可选)
Drive API默认一次最多返回100条结果,若文件夹数量较多,需处理分页逻辑:const fetchGoogleDriveFiles = async () => { try { let allFolders = []; let pageToken = null; do { const response = await fetch( `https://www.googleapis.com/drive/v3/files?q=mimeType='application/vnd.google-apps.folder'&fields=files(id,name,mimeType,parents),nextPageToken&pageToken=${pageToken || ""}`, { method: "GET", headers: { Authorization: `Bearer ${session.accessToken}`, }, } ); if (!response.ok) { console.error("请求Google Drive文件失败:", response.status); break; } const data = await response.json(); allFolders = [...allFolders, ...data.files]; pageToken = data.nextPageToken; } while (pageToken); console.log("所有Google Drive文件夹:", allFolders); } catch (error) { console.error("请求Google Drive文件失败:", error); } };
注意事项:
- 权限范围越大,用户授权时的信任门槛越高,优先用
readonly权限满足需求 - 确保Google Cloud控制台中已启用Drive API,且配置了正确的OAuth同意屏幕(面向外部用户时)
内容的提问来源于stack exchange,提问作者user14670265
相关产品推荐
相关产品推荐

