Skip to content

Commit

Permalink
feat: 增加 state 参数,以防止跨站请求伪造
Browse files Browse the repository at this point in the history
  • Loading branch information
CaoMeiYouRen committed Oct 7, 2024
1 parent 7945000 commit 210f5a5
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
3 changes: 3 additions & 0 deletions src/pages/oauth.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ import { Hono } from 'hono'
import { FC } from 'hono/jsx'
import { Layout } from '@/layout/layout'
import { QRCODE_URL } from '@/env'
import { generateRandomString } from '@/utils/helper'

const app = new Hono()

// 通过验证码登录的前端表单
const OAuthLogin: FC = () => {
const state = generateRandomString(16)
return (
<Layout title="验证码登录">
<div className="max-w-md mx-auto p-6 bg-white shadow-md rounded-lg">
Expand All @@ -18,6 +20,7 @@ const OAuthLogin: FC = () => {
</p>
</div>
<form action="/auth/loginByOAuth" method="post">
<input type="hidden" name="state" value={state} />
<div className="mb-4">
<label htmlFor="code" className="block text-sm font-medium text-gray-700">验证码</label>
<input type="text" name="code" id="code" className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
Expand Down
10 changes: 8 additions & 2 deletions src/routes/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ app.post('/loginByOAuth', async (c) => {
} else if (contentType === 'application/json') {
body = await c.req.json()
}
const { code } = body
const { code, state } = body
const scene = 'login'
const verifyCodeRepository = (await getDataSource()).getRepository(VerifyCode)
const verifyCode = await verifyCodeRepository.findOne({ where: { code, scene, used: false, expiredAt: MoreThanOrEqual(dayjs().add(-5, 'minutes').toDate()) }, relations: ['user'] })
Expand All @@ -79,7 +79,13 @@ app.post('/loginByOAuth', async (c) => {
const user = verifyCode.user
const accessCode = await createAccessCode(user)
// 将授权码返回给客户端
const redirectUrl = `${OAUTH_REDIRECT_URL}?accessCode=${accessCode.code}`
const query = new URLSearchParams({
accessCode: accessCode.code,
state,
})
const url = new URL(OAUTH_REDIRECT_URL)
url.search = query.toString()
const redirectUrl = url.toString()
return c.redirect(redirectUrl, 302)
})

Expand Down

0 comments on commit 210f5a5

Please sign in to comment.