@ crossmint/ 客户端- sdk- auth
这个SDK为用户在客户端的Crossmint驱动应用程序中认证用户提供了一套工具. 它简化了处理认证令牌,管理用户会话,以及将各种认证方法纳入你的网络应用程序的过程.
安装
要安装 SDK, 您可以使用 npm 或 线 :
npm install @crossmint/client-sdk-auth
使用量
要在您的应用程序中使用 SDK, 请遵循这些步骤 :
- 导入 SDK 到您的工程中 :
import { createCrossmint, CrossmintAuth } from "@crossmint/client-sdk-auth";
const crossmint = createCrossmint({
apiKey: process.env.CLIENT_CROSSMINT_API_KEY || "",
});
const crossmintAuth = CrossmintAuth.from(crossmint);
- 使用 SDK 认证用户并管理会话 :
// Get the current user
const user = await crossmintAuth.getUser();
// Log out the user and clear cookies
crossmintAuth.logout();
自定义存储提供者
默认情况下,SDK使用浏览器饼干来存储认证材料. 对于没有饼干的环境,如React Introduct,您可以提供自定义的存储提供者.
反应原生存储选项
SDK为React Introduct提供了几种安全的存储执行:
1. 博览会安全站(为博览会应用推荐)
首先安装依赖性 :
npx expo install expo-secure-store
对于 Expo 应用程序,使用 securityStore ,它提供了一个安全的加密存储解决方案:
import * as SecureStore from 'expo-secure-store';
import { ExpoSecureStorage, CrossmintAuth } from "@crossmint/client-sdk-auth";
// Create a custom storage provider using Expo's SecureStore
const storageProvider = new ExpoSecureStorage(SecureStore);
// Initialize auth client with secure storage
const crossmintAuth = CrossmintAuth.from(crossmint, {
storageProvider
});
2. 反应原生加密存储(推荐给非Expo apps)
首先安装依赖性 :
npm install react-native-encrypted-storage
对于香草回放原生应用程序,使用加密Storage:
import EncryptedStorage from 'react-native-encrypted-storage';
import { RNEncryptedStorage, CrossmintAuth } from "@crossmint/client-sdk-auth";
// Create a custom storage provider using react-native-encrypted-storage
const storageProvider = new RNEncryptedStorage(EncryptedStorage);
// Initialize auth client with secure storage
const crossmintAuth = CrossmintAuth.from(crossmint, {
storageProvider
});
执行自定义存储
您可以通过执行 StorageProvider 接口 :
export interface StorageProvider {
get(key: string): string | undefined | Promise<string | undefined>;
set(key: string, value: string, expiresAt?: string): void | Promise<void>;
remove(key: string): void | Promise<void>;
}
使用 Http 只使用饼干的安全设置
为了保证认证材料的安全,可以在后端设置自定义端点,处理刷新认证材料并将其存储于HttpOnly Cookie. 这样,在浏览器中运行的JavaScript无法访问认证材料.
配置自定义刷新路由
在客户端中, 在创建 CrossmintAuth 实例时提供自定义刷新路由 :
const crossmintAuth = CrossmintAuth.from(crossmint, {
refreshRoute: "/api/refresh",
});
这样,SDK会使用提供的路由来刷新符号而不是默认的路由,认证材料可以被存储在HttpOnly Cookie中,这些被绑定在所提供路由的域上.
配置自定义登录路径
由于你现在使用HtpOnly cookie,登录无法发生客户端,因为它无法访问cookie. 可以设置自定义的登录路由来处理登录过程.
在客户端中, 在创建 CrossmintAuth 实例时提供自定义登录路径 :
const crossmintAuth = CrossmintAuth.from(crossmint, {
logoutRoute: "/api/logout",
});
注:根据您所使用的框架,您可能需要在 refreshRoute 财务报告和审定财务报表 logoutRoute 选项.
高级使用
在创建 CrossmintAuthClient 时, 您可以为 符号刷新和登录事件提供回调 :
const crossmintAuth = CrossmintAuth.from(crossmint, {
callbacks: {
onTokenRefresh: (authMaterial) => {
// Handle new authentication material
},
onLogout: () => {
// Handle logout
},
},
});
认证材料
{
"jwt": "...",
"refreshToken": "...",
"user": {
"id": "...",
"email": "..."
}
}
这些调用允许您在刷新符号或用户日志退出时执行自定义动作 .