【发布时间】:2021-10-09 14:28:50
【问题描述】:
我构建了一个显示 GitHub 存储库的简单应用程序。这是应用程序的链接:https://wemake-services-test-client.herokuapp.com(首先,您需要对 GitHub 进行身份验证)。在我看来, fetch 不会发送 httpOnly cookie。点击“登录”并打开控制台:
路由 '/login' 的后端处理程序设置 httpOnly cookie:
import { Request, Response } from 'express';
import { createOAuthAppAuth } from '@octokit/auth-oauth-app';
import cookieOptions from '../cookieOptions';
export default async function login(req: Request, res: Response) {
const code = req.query.code as string;
const appAuth = createOAuthAppAuth({
clientType: 'oauth-app',
clientId: process.env.GITHUB_CLIENT_ID!,
clientSecret: process.env.GITHUB_CLIENT_SECRET!,
});
try {
const userAuth = await appAuth({
type: 'oauth-user',
code,
});
const { token } = userAuth;
res.cookie('ws_token', token, cookieOptions);
res.json({ isAuthenticated: true });
...
然后我让 GET 到 '/user' 路由,该路由具有检查 req.cookies 中是否有 'ws_token' 的 authMiddleware,如果没有则发送状态 401(未授权)。
authMiddleware.ts:
export default function authMiddleware(
req: Request,
res: Response,
next: NextFunction
) {
if (!req.cookies.ws_token) {
res.sendStatus(401);
return;
}
next();
}
所以我在“/user”上收到 401 错误,因为 fetch 没有从客户端发送 httpOnly cookie ws_token。
...
async fetchUser(): Promise<GithubUser> {
const response = await fetch(`${API_URL}/user`, {
headers: {
Accept: 'application/json',
},
credentials: 'include',
});
const user: GithubUser = await response.json();
return user;
}
...
它可以在 localhost 上工作(没有标志 secure 和 domain 设置为 localhost),但不能在 Heroku 上工作。但为什么?如何解决?
源代码:
前端 - https://github.com/standbyoneself/ws-test-client(使用 fetch 调用 API 在 src/services/GithubService.ts 中)
【问题讨论】:
标签: node.js express heroku cookies fetch