跳转到正文

结合 Hono 使用 Stytch Auth ​

本示例展示如何使用 vite 和 react 构建全栈应用,在前端使用 Stytch SDK,在 Cloudflare Workers 上使用 Hono 后端。

遵循这些方式实现的完整示例应用可在这里找到。

安装 ​

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

配置 ​

  1. 创建 Stytch 账户,并选择消费者身份验证(Consumer Authentication)。
  2. 在配置中启用前端 SDK(Frontend SDK)。
  3. 从项目设置获取凭据。

环境变量 ​

后端 Workers 的环境变量放在 .dev.vars 中,前端 Vite 的环境变量放在 .env.local 中。

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

前端 ​

  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

后端 ​

  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

后续步骤 ​

更多文档和资源:

如果你对组织管理、RBAC 和 SSO 等企业 B2B 功能感兴趣,请查看 Stytch B2B 身份验证产品系列。

欢迎在 Stytch Slack 社区中参与讨论、提出问题和建议新功能。

基于 MIT 许可证发布。