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 账户并选择“消费者身份验证”。

    ¥Create a Stytch account and select Consumer Authentication.

  2. 配置 中启用前端 SDK。

    ¥Enable the Frontend SDK in Configuration.

  3. 项目设置 获取你的凭据。

    ¥Get your credentials from Project Settings.

环境变量

¥Environment Variables

后端 Workers 环境变量放在 .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 客户端实例。

    ¥Wrap your application with the <StytchProvider /> component and pass it an instance of the Stytch UI Client.

  2. 使用 <StytchLogin /> 组件登录用户。请参阅 组件 Playground,了解不同的身份验证方法和可用的样式自定义示例。

    ¥Use the <StytchLogin /> component to log the user in. See the Component Playground for examples of different authentication methods and style customizations available.

  3. 用户登录后,可以使用 useStytchUser() hook 检索活动用户数据。

    ¥After the user is logged in, the useStytchUser() hook can be used to retrieve the active user data.

  4. 用户的会话信息将自动存储为 cookie 并提供给你的后端。

    ¥The user's session information will automatically be stored as a cookie and made available to your backend.

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。

    ¥Wrap protected endpoints with a Consumer.authenticateSessionLocal() middleware to authenticate the Stytch session JWT.

  2. 使用 Consumer.getStytchSession(c) 方法在路由中检索 Stytch 会话信息。

    ¥Use the Consumer.getStytchSession(c) method to retrieve the Stytch session information within a route.

  3. 需要完整用户对象的路由可以使用 Consumer.authenticateSessionRemote() 方法向 Stytch 服务器执行网络调用。

    ¥Routes that require the full user object can use the Consumer.authenticateSessionRemote() method to perform a network call to Stytch servers.

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 v4.11 中文网 - 粤ICP备13048890号