-
Notifications
You must be signed in to change notification settings - 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
Open
fishwww-ww
wants to merge
3
commits into
labring:test/html
Choose a base branch
from
fishwww-ww:feat/twoTokens
base: test/html
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 || ''); | ||
fishwww-ww marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
} 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; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -183,8 +183,7 @@ const MarkdownRender = ({ | |
'base', | ||
'form', | ||
'input', | ||
'button', | ||
'img' | ||
'button' | ||
] | ||
} | ||
] | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
39 changes: 39 additions & 0 deletions
39
projects/app/src/pages/api/support/user/account/generateCsrfToken.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
}; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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