UNPKG

zskj-auth-sdk

Version:

A reusable authentication SDK based on React, TypeScript

93 lines (76 loc) 1.9 kB
## 1、安装SDK ``` # npm npm install zskj-auth-sdk # yarn yarn add zskj-auth-sdk # pnpm pnpm install zskj-auth-sdk ``` ## 2、在项目入口文件添加Provider和初始化SDK ``` import { AuthProvider, initAuthSdk } from 'zskj-auth-sdk'; function App() { const [initState, setInitState] = useState(false); useEffect(() => { <!-- 初始化SDK --> initAuthSdk({ serverUrl: 'https://api.xxx.com', clientId: 'your-client-id', organizationName: 'your-organization-name', appName: 'your-app-name', redirectPath: 'optional, redirect-path, default: /callback', signinPath: 'optional, signin-path', }); setInitState(true); }, []); if (!initState) { return; } return ( <> <!-- 提供入口Provider --> <AuthProvider> <Main /> </AuthProvider> </> ); ``` ## 3、api调用【推荐,兼容各种场景】 ``` import { useAuth } from 'zskj-auth-sdk'; function Page() { const { apiLogin } = useAuth(); const onClickStart = async () => { const resp = await apiLogin('common', { username: 'xxx', password: 'xxx', autoSignin: true}); console.log(resp); // 这里就是返回access_token,refresh_token等信息 } return ( <div> <h1>{user?.username}</h1> <h1>{user?.password}</h1> <h1>{user?.autoSignin}</h1> <button onClick={onClickStart}>Sign In</button> </div> ); } ``` ## 4、react-hook调用【会跳转默认登录页面,无法自定义登录页面】 ``` import { useAuth } from 'zskj-auth-sdk'; function Page() { const { login, logout, setAuthCallback } = useAuth(); useEffect(() => { <!-- 设置登录成功回答, --> setAuthCallback(() => { // 登录成功回调 }); }) return ( <div> <h1>{user?.name}</h1> <button onClick={() => login('租户ID')}>Sign In</button> </div> ); } ```