Skip to content

使用 Stytch 进行身份验证 Hono

🌐 Stytch Auth with Hono

这个示例展示了如何使用 Stytch 前端 SDK 和 Hono 后端在 Cloudflare Workers 上使用 vitereact 设置全栈应用。

🌐 This example shows how to set up a full-stack application with Stytch Frontend SDKs and Hono backend on Cloudflare Workers with vite and react.

使用这些原则的完整示例应用可以在这里找到。

🌐 A complete example application using these principles can be found here.

安装

🌐 Installation

sh
# Backend
npm install @hono/stytch-auth stytch

# Frontend
npm install @stytch/react @stytch/vanilla-js
sh
# Backend
yarn add @hono/stytch-auth stytch

# Frontend
yarn add @stytch/react @stytch/vanilla-js
sh
# Backend
pnpm add @hono/stytch-auth stytch

# Frontend
pnpm add @stytch/react @stytch/vanilla-js
sh
# Backend
bun add @hono/stytch-auth stytch

# Frontend
bun add @stytch/react @stytch/vanilla-js

设置

🌐 Setup

  1. 创建一个 Stytch 账户并选择 消费者认证
  2. 配置 中启用 前端 SDK
  3. 项目设置 获取你的凭证。

环境变量

🌐 Environment Variables

后端工作者的环境变量放在 .dev.vars。前端 Vite 的环境变量放在 .env.local

🌐 Backend Workers env vars go in .dev.vars. Frontend Vite env vars go in .env.local.

Plain
STYTCH_PROJECT_ID=project-live-xxx
STYTCH_PROJECT_SECRET=secret-live-xxx
Plain
VITE_STYTCH_PUBLIC_TOKEN=public-token-live-xxx

前端

🌐 Frontend

  1. 使用 <StytchProvider /> 组件封装你的应用,并传入一个 Stytch UI 客户端的实例。
  2. 使用 <StytchLogin /> 组件登录用户。有关不同身份验证方法和可用样式自定义的示例,请参见 组件游乐场
  3. 用户登录后,可以使用 useStytchUser() 钩子来获取活跃用户数据。
  4. 用户的会话信息将自动存储为 cookie 并提供给你的后端。
tsx
import React from 'react'
import {StytchUIClient} from '@stytch/vanilla-js';
import {StytchProvider, useStytchUser} from '@stytch/react';
import LoginPage from './LoginPage'
import Dashboard from './Dashboard'

const stytch = new StytchUIClient(import.meta.env.VITE_STYTCH_PUBLIC_TOKEN ?? '');

function AppContent() {
  const { user, isInitialized } = useStytchUser()

  if (!isInitialized) return <div>Loading...</div>
  return user ? <Dashboard /> : <LoginPage />
}

function App() {
  return (
    <StytchProvider stytch={stytch}>
      <AppContent />
    </StytchProvider>
  )
}

export default App
tsx
import React from 'react'
import { StytchLogin } from '@stytch/react'
import { Products, OTPMethods } from '@stytch/vanilla-js'

const loginConfig = {
  products: [Products.otp],
  otpOptions: {
    expirationMinutes: 10,
    methods: [OTPMethods.Email],
  },
}

const LoginPage = () => {
  return <StytchLogin config={loginConfig} />
}

export default LoginPage
tsx
import React from 'react'
import { useStytchUser, useStytch } from '@stytch/react'

const Dashboard = () => {
  const { user } = useStytchUser()
  const stytchClient = useStytch()

  const handleLogout = () => stytchClient.session.revoke()

  return (
    <div style={{ maxWidth: '600px', margin: '2rem auto' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        <h1>Dashboard</h1>
        <button onClick={handleLogout}>Logout</button>
      </div>
      <p>Welcome, {user.emails[0]?.email}!</p>
    </div>
  )
}

export default Dashboard

后端

🌐 Backend

  1. 使用 Consumer.authenticateSessionLocal() 中间件封装受保护的端点,以验证 Stytch 会话 JWT。
  2. 在路由中使用 Consumer.getStytchSession(c) 方法来获取 Stytch 会话信息。
  3. 需要完整用户对象的路由可以使用 Consumer.authenticateSessionRemote() 方法来对 Stytch 服务器执行网络调用。
src/index.ts
ts
import { Hono } from 'hono'
import { Consumer } from '@hono/stytch-auth'

const app = new Hono()

// Public route
app.get('/health', (c) => c.json({ status: 'ok' }))

// Protected route with local authentication (very fast)
app.get('/api/local', Consumer.authenticateSessionLocal(), (c) => {
  const session = Consumer.getStytchSession(c)
  return c.json({
    message: 'Protected data',
    sessionId: session.session_id,
  })
})

// Protected route with remote authentication & full user data
app.get('/api/remote', Consumer.authenticateSessionRemote(), (c) => {
  const session = Consumer.getStytchSession(c)
  const user = Consumer.getStytchUser(c)
  return c.json({
    message: 'Protected data',
    sessionId: session.session_id,
    firstName: user.name.first_name,
  })
})

export default app

后续步骤

🌐 Next Steps

更多文档和资源:

🌐 Additional documentation and resources:

对企业级 B2B 功能感兴趣,例如组织管理、RBAC 和单点登录 (SSO)?请查看 Stytch B2B 身份验证 产品线。

🌐 Interested in Enterprise B2B features like Organization Management, RBAC, and SSO? See the Stytch B2B Authentication product line.

加入讨论,提问,并在Stytch Slack 社区中建议新功能。

🌐 Join the discussion, ask questions, and suggest new features in the Stytch Slack Community.

Hono 中文网 - 粤ICP备13048890号