-
Couldn't load subscription status.
- Fork 6.7k
feat: csrf, two tokens verify #5692
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: test/html
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| import type { NextApiRequest, NextApiResponse } from 'next'; | ||
| import { verifyCsrfToken } from '../../support/permission/auth/common'; | ||
| import { generateCsrfToken } from '../../../../projects/app/src/web/support/user/api'; | ||
|
|
||
| export const withCSRFCheck = async ( | ||
| req: NextApiRequest, | ||
| res: NextApiResponse, | ||
| isCSRFCheck: boolean = true | ||
| ) => { | ||
| if (!isCSRFCheck) return; | ||
|
|
||
| try { | ||
| const csrfToken = await getCsrfTokenFromRequest(req); | ||
| verifyCsrfToken(csrfToken); | ||
| } catch (error) { | ||
| return res.status(403).json({ | ||
| code: 403, | ||
| message: 'Invalid CSRF token' | ||
| }); | ||
| } | ||
| }; | ||
|
|
||
| async function getCsrfTokenFromRequest(req: NextApiRequest): Promise<string | null> { | ||
| const headerToken = req.headers['x-csrf-token']; | ||
|
|
||
| if (!headerToken || typeof headerToken !== 'string') { | ||
| const { csrfToken } = await generateCsrfToken(); | ||
| return csrfToken; | ||
| } | ||
|
|
||
| return headerToken; | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -183,8 +183,7 @@ const MarkdownRender = ({ | |
| 'base', | ||
| 'form', | ||
| 'input', | ||
| 'button', | ||
| 'img' | ||
| 'button' | ||
| ] | ||
| } | ||
| ] | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| import type { NextApiRequest, NextApiResponse } from 'next'; | ||
| import { NextAPI } from '@/service/middleware/entry'; | ||
| import { authCert, setCsrfCookie } from '@fastgpt/service/support/permission/auth/common'; | ||
| import jwt from 'jsonwebtoken'; | ||
| import type { ApiRequestProps, ApiResponseType } from '@fastgpt/service/type/next'; | ||
|
|
||
| export type GenerateCsrfTokenQuery = {}; | ||
| export type GenerateCsrfTokenBody = {}; | ||
| export type GenerateCsrfTokenResponse = { | ||
| csrfToken: string; | ||
| expiresAt: number; | ||
| }; | ||
|
|
||
| async function handler( | ||
| req: ApiRequestProps<GenerateCsrfTokenBody, GenerateCsrfTokenQuery>, | ||
| res: ApiResponseType<GenerateCsrfTokenResponse> | ||
| ): Promise<GenerateCsrfTokenResponse> { | ||
| const jwtSecret = process.env.TOKEN_KEY || 'any'; | ||
| const expiresAt = Math.floor(Date.now() / 1000) + 60 * 60; | ||
| const csrfToken = jwt.sign( | ||
| { | ||
| type: 'csrf', | ||
| exp: expiresAt | ||
| }, | ||
| jwtSecret, | ||
| { | ||
| algorithm: 'HS256' | ||
| } | ||
| ); | ||
|
|
||
| setCsrfCookie(res, csrfToken); | ||
|
|
||
| return { | ||
| csrfToken, | ||
| expiresAt | ||
| }; | ||
| } | ||
|
|
||
| export default NextAPI(handler, { isCSRFCheck: false }); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| import { generateCsrfToken } from '@/web/support/user/api'; | ||
|
|
||
| const CSRF_TOKEN_STORAGE_KEY = 'csrf_token'; | ||
| const CSRF_EXPIRES_STORAGE_KEY = 'csrf_expires'; | ||
|
|
||
| interface CsrfTokenData { | ||
| token: string; | ||
| expiresAt: number; | ||
| } | ||
|
|
||
| export const getCsrfToken = async (): Promise<string> => { | ||
| const storedToken = getStoredToken(); | ||
|
|
||
| if (storedToken && isTokenValid(storedToken.expiresAt)) { | ||
| return storedToken.token; | ||
| } | ||
|
|
||
| return fetchNewToken(); | ||
| }; | ||
|
|
||
| const getStoredToken = (): CsrfTokenData | null => { | ||
| const token = localStorage.getItem(CSRF_TOKEN_STORAGE_KEY); | ||
| const expiresAt = localStorage.getItem(CSRF_EXPIRES_STORAGE_KEY); | ||
|
|
||
| if (token && expiresAt) { | ||
| return { | ||
| token, | ||
| expiresAt: parseInt(expiresAt, 10) | ||
| }; | ||
| } | ||
|
|
||
| return null; | ||
| }; | ||
|
|
||
| const isTokenValid = (expiresAt: number): boolean => { | ||
| const currentTime = Math.floor(Date.now() / 1000); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 怎么还 /1000,直接比较 timestamp 不就行了吗 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. jwt标准是用秒级时间戳来生成签名, 这里 /1000 是为与jwt的秒级别统一 |
||
| const bufferTime = 10 * 60; | ||
|
|
||
| return expiresAt > currentTime + bufferTime; | ||
| }; | ||
|
|
||
| const fetchNewToken = async (): Promise<string> => { | ||
| const csrfTokenData = await generateCsrfToken(); | ||
|
|
||
| if (csrfTokenData.csrfToken && csrfTokenData.expiresAt) { | ||
| localStorage.setItem(CSRF_TOKEN_STORAGE_KEY, csrfTokenData.csrfToken); | ||
| localStorage.setItem(CSRF_EXPIRES_STORAGE_KEY, csrfTokenData.expiresAt.toString()); | ||
| return csrfTokenData.csrfToken; | ||
| } | ||
| return ''; | ||
| }; | ||
|
|
||
| export const clearCsrfToken = (): void => { | ||
| localStorage.removeItem(CSRF_TOKEN_STORAGE_KEY); | ||
| localStorage.removeItem(CSRF_EXPIRES_STORAGE_KEY); | ||
| }; | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,9 +1,12 @@ | ||
| import { loginOut } from '@/web/support/user/api'; | ||
| import { clearCsrfToken } from '@/web/common/utils/csrfToken'; | ||
|
|
||
| export const clearToken = () => { | ||
| export const clearToken = async () => { | ||
| try { | ||
| clearCsrfToken(); | ||
| return loginOut(); | ||
| } catch (error) { | ||
| clearCsrfToken(); | ||
| error; | ||
| } | ||
| }; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
verifyCsrfToken 和 generateCsrfToken 应该放在一个模块里面
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
前端检测到cookie即将过期, 要主动请求generateCsrfToken, 所以generateCsrfToken放在了api模块, 便于请求; verifyCsrfToken则放在中间件模块用于验证CsrfToken