npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

lgsso-sdk

v1.3.1

Published

无框架依赖的单点登录SDK

Readme

lgsso-sdk

LG-SSO SDK 是一个无框架依赖的单点登录(SSO)JavaScript 库,提供 token 管理、登录状态维护、注销、跨应用跳转等功能,可帮助 Web 应用快速集成 SSO 认证机制。

一、安装

支持 npm 和 yarn 两种包管理工具,执行对应命令完成安装:

\# 使用 npm 安装

npm install lgsso-sdk

\# 使用 yarn 安装

yarn add lgsso-sdk

二、引入方式

提供「默认实例」和「自定义实例」两种引入方式,根据项目需求选择:

// 1. 引入默认实例(推荐单 SSO 配置场景)

import lgsso from 'lgsso-sdk';

// 2. 创建自定义实例(多 SSO 配置场景,如多系统对接)

import { createSSO } from 'lgsso-sdk';

const customSSO = createSSO();

三、初始化配置

⚠️ 重要:使用 SDK 所有核心方法前,必须先调用 init() 方法完成初始化,否则会抛出「未初始化」错误。

3.1 初始化示例代码

lgsso.init({

  accessCodeKey: 'accessCode',    // accessCode 在 URL 中的参数名

  tokenKey: 'scm\_token',          // token 在存储中的键名

  timeout: 5000,                  // 请求超时时间(单位:毫秒)

  headers: {},                    // 自定义请求头(如项目标识、Content-Type)

  tokenApi: '/api/token',         // 通过 accessCode 获取 token 的 API 地址(必填)

  refreshCodeApi: '/api/refresh', // 刷新 accessCode 的 API 地址

  logoutApi: '/api/logout',       // 注销 API 地址

  logOutUrl: '/login',            // 登录页面 URL(无 token 时自动跳转)

  storage: localStorage,          // 存储方式(支持 localStorage/sessionStorage)

  oldPwdKey: 'oldPwd',            // 旧密码在请求参数中的键名(用于修改密码)

  newPwdKey: 'newPwd',            // 新密码在请求参数中的键名(用于修改密码)

  typeKey: 'type',            // 类型在请求参数中的键名(用于修改密码)

  codeKey: 'code',            // 验证码在请求参数中的键名(用于修改密码)

  changePasswordApi: '/api/change-pwd' // 修改密码的 API 地址(用于修改密码功能)

  sendCaptchaCodeApi: '/api/sendCaptchaCode' // 获取手机验证码 API 地址 (用于修改密码功能)
})

.then(result => {

  console.log('初始化结果:', result); // 打印初始化状态(成功/失败信息)

});

3.2 配置参数说明

| 参数名 | 类型 | 默认值 | 说明 | | ----------------- | ------ | ------------ | -------------------------------------------------- | | accessCodeKey | String | 'accessCode' | accessCode 在 URL 中的参数名(如 ?accessCode=xxx) | | tokenKey | String | 'scm_token' | token 在 storage 中的存储键名(用于读取 / 删除 token) | | timeout | Number | 5000 | 请求超时时间(单位:ms),超时后触发错误 | | headers | Object | {} | 全局自定义请求头,所有 SDK 发起的请求均携带 | | tokenApi | String | '' | 通过 accessCode 获取 token 的 API 地址(必填,否则无法初始化) | | refreshCodeApi | String | '' | 刷新 accessCode 的 API 地址(跨应用跳转需配置) | | logoutApi | String | '' | 注销 API 地址(未配置时仅清除本地 token) | | logOutUrl | String | '' | 登录页面 URL(无有效 token 时自动跳转,必填) | | storage | Object | localStorage | 存储介质,需实现 setItem(key, value)getItem(key) 方法 | | oldPwdKey | String | 'oldPwd' | 旧密码在请求参数中的键名(修改密码功能用) | | newPwdKey | String | 'newPwd' | 新密码在请求参数中的键名(修改密码功能用) | typeKey | String | 'type' | 类型在请求参数中的键名(修改密码功能用) | codeKey | String | 'code' | 验证码在请求参数中的键名(修改密码功能用) | | changePasswordApi | String | '' | 修改密码的 API 地址(修改密码功能需配置,必填) | | sendCaptchaCodeApi | String | '' | 获取手机验证码 API 地址(修改密码功能需配置,必填) |

四、核心方法

所有方法均返回 Promise 对象,支持 async/await.then() 链式调用,便于异步流程控制。

4.1 init(options)

功能

初始化 SDK,完成配置合并、参数验证、AccessCode 换 Token、无 Token 跳转登录页等操作。

参数

  • options:Object 类型,配置选项(详见「3.1 初始化示例代码」)

返回

  • Promise<Object>:初始化结果,结构如下:
{

&#x20; code: 0,          // 状态码(0:成功,-100:初始化错误)

&#x20; msg: '初始化成功', // 提示信息

&#x20; success: true,    // 成功标识(true/false)

&#x20; data: null        // 附加数据(如 Token,仅部分场景返回)

}

4.2 getToken()

功能

获取存储在本地的 Token 值。

参数

返回

  • String|null:Token 值(存在则返回字符串,不存在 / 过期则返回 null)

示例代码

const token = lgsso.getToken();

if (token) {

&#x20; console.log('当前有效 Token:', token);

&#x20; // 可用于非 SDK 发起的接口请求(如自定义 axios 实例)

} else {

&#x20; console.log('无有效 Token,需重新登录');

}

4.3 removeToken()

功能

删除本地存储的 Token(仅清除本地数据,不调用 logoutApi)。

参数

返回

示例代码

// 清除本地 Token

lgsso.removeToken();

console.log('Token 已清除:', lgsso.getToken()); // 输出 null

4.4 logout()

功能

执行退出登录流程:调用 logoutApi(若配置)→ 清除本地 Token → 跳转到登录页。

参数

返回

  • Promise<Object>:退出结果,结构如下:
{

&#x20; code: 0,          // 状态码(0:成功,-102:无 logoutApi,-103:退出失败)

&#x20; msg: '退出成功',   // 提示信息

&#x20; success: true     // 成功标识(true/false)

}

示例代码

lgsso.logout()

.then(result => {

&#x20; if (result.code === 0) {

&#x20;   console.log('退出成功,已跳转至登录页');

&#x20; } else {

&#x20;   console.warn('退出警告:', result.msg);

&#x20; }

})

.catch(error => {

&#x20; console.error('退出失败:', error.message);

});

4.5 toUrl(redirectUrl, target)

功能

跨应用跳转核心方法:通过当前 Token 刷新 AccessCode → 将 AccessCode 拼接至目标 URL → 执行跳转。

参数

  1. redirectUrl:String 类型(必填),目标跳转地址(如 https://other-app.example.com

  2. target:String 类型(可选),跳转方式('_self':当前页面跳转,默认;'_blank':新窗口打开)

返回

  • Promise<Object>:跳转准备结果(仅代表 AccessCode 刷新状态,跳转操作同步执行)

示例代码

// 1. 在当前页面跳转到目标应用(默认方式)

lgsso.toUrl('https://other-app.example.com', '\_self')

.then(result => {

&#x20; if (result.code === 0) {

&#x20;   console.log('AccessCode 刷新成功,已跳转');

&#x20; }

})

.catch(error => {

&#x20; console.error('跳转失败:', error.message);

});

// 2. 在新窗口打开目标应用

lgsso.toUrl('https://other-app.example.com', '\_blank')

.catch(error => {

&#x20; console.error('新窗口跳转失败:', error.message);

});

4.6 getAccessCode()

功能

通过当前 Token 刷新 AccessCode(仅获取 AccessCode,不执行跳转,适用于自定义跳转场景)。

参数

返回

  • Promise<Object>:AccessCode 刷新结果,结构如下:
{

&#x20; code: 0,                  // 状态码(0:成功,-105:无 refreshCodeApi,-106:无 Token)

&#x20; msg: 'AccessCode 刷新成功',// 提示信息

&#x20; success: true,            // 成功标识

&#x20; data: 'abc123xyz'         // 新的 AccessCode(成功时返回)

}

示例代码

lgsso.getAccessCode()

.then(result => {

&#x20; if (result.code === 0) {

&#x20;   const accessCode = result.data;

&#x20;   // 自定义跳转逻辑(如拼接多个参数)

&#x20;   const targetUrl = \`https://other-app.example.com?accessCode=\${accessCode}\&timestamp=\${Date.now()}\`;

&#x20;   window.location.href = targetUrl;

&#x20; }

})

.catch(error => {

&#x20; console.error('AccessCode 刷新失败:', error.message);

});

4.7 changePassword(fromData)

功能

调用修改密码 API,更新用户密码(需先配置 changePasswordApioldPwdKeynewPwdKey)。

参数

  • fromData:Object 类型(必填),密码信息对象,需包含 oldPwdKeynewPwdKey 配置对应的键名(默认需包含 oldPwdnewPwd

返回

  • Promise<Object>:密码修改结果,结构如下:
{

&#x20; code: 0,                // 状态码(0:成功,-1:参数缺失,其他:接口错误)

&#x20; msg: '密码修改成功',     // 提示信息

&#x20; success: true           // 成功标识(true/false)

}

示例代码

// 1. 使用默认参数键名(oldPwd、newPwd)

lgsso.changePassword({

&#x20; oldPwd: 'current-password-123', // 旧密码

&#x20; newPwd: 'new-password-456'      // 新密码

})

.then(result => {

&#x20; if (result.code === 0) {

&#x20;   console.log('密码修改成功,建议重新登录');

&#x20;   // 可选:强制退出登录(避免旧 Token 残留)

&#x20;   // lgsso.logout();

&#x20; } else {

&#x20;   console.error('密码修改失败:', result.msg);

&#x20; }

});

// 2. 使用自定义参数键名(如配置 oldPwdKey: 'oldPassword'、newPwdKey: 'newPassword')

lgsso.changePassword({

&#x20; oldPassword: 'current-password-123',

&#x20; newPassword: 'new-password-456'

});

五、错误码说明

| 错误码 | 说明 | 所属场景 | | ---- | -------------------------------------------- | --------------------- | | -1 | 密码修改参数验证错误(如缺少旧密码 / 新密码、参数键名不匹配配置) | 密码修改 | | -100 | 初始化相关错误(如缺少必填配置 tokenApi/logOutUrl、配置无效) | 初始化 | | -101 | 未初始化(调用其他方法前未调用 init()) | 所有方法 | | -102 | 未配置 logoutApi(仅清除本地 Token,不调用后端接口) | 退出登录 | | -103 | 退出登录失败(如 logoutApi 接口报错、网络异常) | 退出登录 | | -104 | 跳转地址为空(redirectUrl 参数未传) | 跨应用跳转 | | -105 | 未配置 refreshCodeApi(无法刷新 AccessCode) | 跨应用跳转 / 获取 AccessCode | | -106 | 未找到有效 Token(本地存储无 Token 或已过期) | 所有需 Token 方法 | | -107 | 跳转失败(如 AccessCode 刷新失败、网络异常) | 跨应用跳转 | | -108 | target 参数无效(仅支持 '_self''_blank') | 跨应用跳转 | | -200 | 非浏览器环境使用 request 方法(如 Node.js 环境) | 所有请求 | | -201 | 响应数据不是有效的 JSON 格式(接口返回格式错误) | 所有请求 | | -202 | 请求超时(超过配置的 timeout 时间) | 所有请求 | | -203 | 网络请求失败(如跨域错误、404/500 状态码) | 所有请求 |

六、完整使用示例

// 初始化 SDK(项目入口处调用,如 main.js)

lgsso.init({

&#x20; tokenApi: '/api/getToken',

&#x20; refreshCodeApi: '/api/refreshCode',

&#x20; logoutApi: '/api/logout',

&#x20; logOutUrl: '/login',

&#x20; oldPwdKey: 'oldPwd',

&#x20; newPwdKey: 'newPwd',

&#x20; changePasswordApi: '/api/change-pwd'

})

.then(initResult => {

&#x20; console.log('初始化结果:', initResult);

&#x20;&#x20;

&#x20; // 1. 获取当前 Token

&#x20; const token = lgsso.getToken();

&#x20; console.log('当前 Token:', token);

&#x20;&#x20;

&#x20; // 2. 绑定「跳转到当前页面」按钮事件

&#x20; document.getElementById('gotoCurrent').addEventListener('click', () => {

&#x20;   lgsso.toUrl('https://other-app.example.com', '\_self')

&#x20;     .catch(err => console.error('跳转失败:', err));

&#x20; });

&#x20;&#x20;

&#x20; // 3. 绑定「跳转到新窗口」按钮事件

&#x20; document.getElementById('gotoNew').addEventListener('click', () => {

&#x20;   lgsso.toUrl('https://other-app.example.com', '\_blank')

&#x20;     .catch(err => console.error('跳转失败:', err));

&#x20; });

&#x20;&#x20;

&#x20; // 4. 绑定「退出登录」按钮事件

&#x20; document.getElementById('logoutBtn').addEventListener('click', () => {

&#x20;   lgsso.logout()

&#x20;     .catch(err => console.error('退出失败:', err));

&#x20; });

&#x20;&#x20;

&#x20; // 5. 绑定「修改密码」按钮事件

&#x20; document.getElementById('changePwdBtn').addEventListener('click', () => {

&#x20;   const oldPwd = document.getElementById('oldPwdInput').value;

&#x20;   const newPwd = document.getElementById('newPwdInput').value;

&#x20;  &#x20;

&#x20;   lgsso.changePassword({ oldPwd, newPwd })

&#x20;     .then(result => {

&#x20;       if (result.code === 0) {

&#x20;         alert('密码修改成功,请重新登录');

&#x20;         lgsso.logout(); // 强制退出登录

&#x20;       } else {

&#x20;         alert('修改失败: ' + result.msg);

&#x20;       }

&#x20;     })

&#x20;     .catch(err => console.error('修改密码异常:', err));

&#x20; });

})

.catch(err => {

&#x20; console.error('初始化失败:', err);

});

七、注意事项

  1. 初始化优先级:必须在项目入口处(如 Vue 的 main.js、React 的 index.js)优先调用 init(),确保后续业务代码使用 SDK 时已完成初始化。

  2. 必填配置检查tokenApilogOutUrl 是初始化必填项,缺少会导致初始化失败(返回 -100 错误)。

  3. 密码修改前置条件:使用 changePassword() 前,需确保配置 changePasswordApioldPwdKeynewPwdKey,且参数键名与配置一致。

  4. 跨应用跳转前提:使用 toUrl() 跳转时,目标应用需集成相同 SSO 逻辑,且当前应用已配置 refreshCodeApi

  5. 安全建议:密码修改成功后,建议调用 logout() 强制用户重新登录,避免旧 Token 残留导致安全风险。

  6. 环境限制:SDK 依赖 localStoragewindow 等浏览器 API,Node.js 环境仅支持 getConfig() 等无依赖方法。

  7. target** 参数限制**:toUrl() 方法的 target 参数仅支持 '_self''_blank',默认使用 '_self'

(注:文档部分内容可能由 AI 生成)