1.0.2 • Published 5 months ago

instant-oauthback v1.0.2

Weekly downloads
-
License
MIT
Repository
-
Last release
5 months ago

instant-oauth

一个灵活的Node.js OAuth认证库,目前支持GitHub OAuth认证。

特性

  • 简单易用的API
  • 完整的TypeScript支持
  • 内置GitHub OAuth支持
  • 灵活的配置选项

安装

npm install instant-oauth
# 或者
yarn add instant-oauth

使用方法

基本使用

import { OAuth } from 'instant-oauth';

// 创建OAuth实例
const oauth = new OAuth('github', {
  clientId: 'your_github_client_id',
  clientSecret: 'your_github_client_secret',
  callbackUrl: 'http://localhost:3000/auth/github/callback',
  scope: ['user']
});

// 获取授权URL
const authUrl = oauth.getAuthUrl();

// 处理OAuth回调
async function handleCallback(code: string) {
  try {
    const userInfo = await oauth.authenticate(code);
    console.log('用户信息:', userInfo);
  } catch (error) {
    console.error('认证失败:', error);
  }
}

Express中使用

import express from 'express';
import { OAuth } from 'instant-oauth';

const app = express();
const oauth = new OAuth('github', {
  clientId: 'your_github_client_id',
  clientSecret: 'your_github_client_secret',
  callbackUrl: 'http://localhost:3000/auth/github/callback',
  scope: ['user']
});

// 重定向到GitHub登录页面
app.get('/auth/github', (req, res) => {
  const authUrl = oauth.getAuthUrl();
  res.redirect(authUrl);
});

// 处理GitHub回调
app.get('/auth/github/callback', async (req, res) => {
  const { code } = req.query;
  try {
    const userInfo = await oauth.authenticate(code as string);
    res.json(userInfo);
  } catch (error) {
    res.status(500).json({ error: '认证失败' });
  }
});

app.listen(3000);

API文档

OAuth类

构造函数

new OAuth(provider: 'github', options: OAuthOptions)

参数:

  • provider: 目前仅支持 'github'
  • options: 配置选项
    • clientId: OAuth应用的客户端ID
    • clientSecret: OAuth应用的客户端密钥
    • callbackUrl: 回调URL
    • scope: 授权范围数组

方法

getAuthUrl()

获取OAuth授权URL。

返回值:string - 授权URL

authenticate(code: string)

使用授权码完成OAuth认证流程。

参数:

  • code: 从OAuth回调中获取的授权码

返回值:Promise<OAuthUserInfo> - 用户信息

许可证

MIT

1.0.2

5 months ago

1.0.1

5 months ago

1.0.0

5 months ago