Token导航 LogoToken导航TokenDH.com
研究检索敏感数据clawhub未标认证来源可访问clear审计提醒

mcp-oauthMCP OAuth 搜索

Agent Skill

用于辅助安全审计、权限检查、凭据风险、认证流程和常见漏洞排查。它适合让 Agent 梳理敏感配置、检查依赖风险、分析鉴权逻辑或生成安全复核清单。使用时不能把工具输出直接当最终结论,涉及密钥、令牌、用户数据或生产系统时,应先确认最小权限、脱敏方式和操作边界。

总安装

6,432

周安装

268

GitHub Stars

公开资料未说明

下载量

2,144
OpenClaw

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

MIT-0

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:mcp-oauth(MCP OAuth 搜索)
来源仓库:https://github.com/lucaperret/mcp-oauth
安装命令:
openclaw skills install mcp-oauth
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 OpenClaw 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

ClawHubOpenClaw
openclaw skills install mcp-oauth

简介

为远程MCP服务器添加OAuth 2.0 PKCE认证。

  • 增强工具调用时的身份合法性验证。mcp-oauth 属于研究检索类 Skill,可作为该场景下的辅助能力补充。
  • 适用于需要保护敏感操作的私有部署场景。
  • 必须妥善保管客户端密钥与回调地址。适用宿主包括 OpenClaw,接入前应确认版本、权限和运行环境要求。
  • 建议配合审计日志监控异常登录尝试。

SKILL.md

name
mcp-oauth
description
Add OAuth 2.0 PKCE authentication to a remote MCP server. Use this skill whenever the user wants to add authentication to an MCP server, protect MCP tools with OAuth, implement login flow for an MCP connector, add user auth to an MCP endpoint, or set up token-based access for MCP. Also triggers on: 'MCP OAuth', 'MCP authentication', 'withMcpAuth', 'MCP login flow', 'protect MCP endpoint', 'MCP token auth', 'dynamic client registration MCP', 'Claude connector OAuth'. Even if the user just says 'add auth to my MCP server' or 'my MCP server needs login', use this skill.
license
MIT
metadata
author
lucaperret
version
1.0.0
openclaw
emoji
\F512
homepage
https://github.com/lucaperret/agent-skills

OAuth 2.0 PKCE for MCP Servers

Add production-ready OAuth authentication to a remote MCP server. This implements the full MCP authorization spec — discovery, dynamic client registration, PKCE authorization, token exchange, and refresh.

When you need this

Your MCP server accesses user-specific data (their account, their files, their playlists). Without auth, anyone with your server URL could access anyone's data. OAuth lets each user authenticate with their own credentials and get their own token.

Architecture overview

Your MCP server plays two roles:

  1. OAuth server for MCP clients (Claude, Smithery) — issues your own tokens
  2. OAuth client to the upstream service (Tidal, GitHub, Slack, etc.) — exchanges for their tokens
MCP Client (Claude) → Your OAuth Server → Upstream Service (e.g., Tidal)
     │                      │                        │
     │  1. Discover OAuth   │                        │
     │  2. Register client  │                        │
     │  3. Authorize        │──→ 4. Redirect to      │
     │                      │      upstream login ──→ │
     │                      │  ←── 5. Callback ──────│
     │  ←── 6. Auth code    │                        │
     │  7. Exchange token   │                        │
     │  8. Call tools ─────→│──→ 9. API calls ──────→│

Required endpoints

1. OAuth Discovery

app/.well-known/oauth-authorization-server/route.ts:

import { NextResponse } from 'next/server';

const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL || 'https://your-domain.com';

export async function GET() {
  return NextResponse.json({
    issuer: SITE_URL,
    authorization_endpoint: `${SITE_URL}/api/authorize`,
    token_endpoint: `${SITE_URL}/api/token`,
    registration_endpoint: `${SITE_URL}/api/register`,
    response_types_supported: ['code'],
    grant_types_supported: ['authorization_code', 'refresh_token'],
    code_challenge_methods_supported: ['S256'],
    token_endpoint_auth_methods_supported: ['none'],
  }, {
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, OPTIONS',
    },
  });
}

export async function OPTIONS() {
  return new NextResponse(null, {
    status: 204,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type, Authorization',
    },
  });
}

2. Protected Resource Metadata

app/.well-known/oauth-protected-resource/route.ts:

import { protectedResourceHandler, metadataCorsOptionsRequestHandler } from 'mcp-handler';

const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL || 'https://your-domain.com';

export const GET = protectedResourceHandler({
  authServerUrls: [SITE_URL],
  resourceUrl: SITE_URL,
});

export const OPTIONS = metadataCorsOptionsRequestHandler();

3. Dynamic Client Registration (RFC 7591)

MCP clients register themselves before starting the auth flow.

app/api/register/route.ts:

import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';

export async function POST(req: NextRequest) {
  const body = await req.json().catch(() => ({}));
  const clientId = crypto.randomBytes(16).toString('hex');

  return NextResponse.json({
    client_id: clientId,
    client_name: body.client_name || 'MCP Client',
    redirect_uris: body.redirect_uris || [],
    grant_types: ['authorization_code', 'refresh_token'],
    response_types: ['code'],
    token_endpoint_auth_method: 'none',
  }, { status: 201 });
}

4. Authorization Endpoint

Validates the request, stores session in Redis, redirects to upstream OAuth.

app/api/authorize/route.ts:

import { NextRequest, NextResponse } from 'next/server';

export async function GET(req: NextRequest) {
  const params = req.nextUrl.searchParams;
  const redirectUri = params.get('redirect_uri');
  const state = params.get('state');
  const codeChallenge = params.get('code_challenge');

  if (!redirectUri || !state || !codeChallenge) {
    return NextResponse.json(
      { error: 'invalid_request', error_description: 'Missing required parameters' },
      { status: 400 },
    );
  }

  // Validate redirect_uri — allow known MCP clients
  const url = new URL(redirectUri);
  const isAllowed =
    url.hostname === 'claude.ai' ||
    url.hostname === 'claude.com' ||
    url.hostname === 'api.smithery.ai' ||
    url.hostname === 'localhost' ||
    url.hostname === '127.0.0.1';

  if (!isAllowed) {
    return NextResponse.json(
      { error: 'invalid_request', error_description: 'redirect_uri not allowed' },
      { status: 400 },
    );
  }

  // Generate PKCE for upstream OAuth
  const upstreamVerifier = crypto.randomBytes(32).toString('base64url');
  const upstreamChallenge = crypto
    .createHash('sha256')
    .update(upstreamVerifier)
    .digest('base64url');
  const sessionId = crypto.randomBytes(16).toString('hex');

  // Store in Redis (10 min TTL)
  await redis.set(`session:${sessionId}`, JSON.stringify({
    redirectUri, state, codeChallenge,
    upstreamVerifier, upstreamState: sessionId,
  }), { ex: 600 });

  // Redirect to upstream OAuth (replace with your service)
  const upstreamUrl = new URL('https://upstream-service.com/authorize');
  upstreamUrl.searchParams.set('client_id', 'YOUR_CLIENT_ID');
  upstreamUrl.searchParams.set('response_type', 'code');
  upstreamUrl.searchParams.set('redirect_uri', `${SITE_URL}/api/callback`);
  upstreamUrl.searchParams.set('code_challenge', upstreamChallenge);
  upstreamUrl.searchParams.set('code_challenge_method', 'S256');
  upstreamUrl.searchParams.set('state', sessionId);

  return NextResponse.redirect(upstreamUrl.toString());
}

5. Callback (from upstream)

app/api/callback/route.ts:

export async function GET(req: NextRequest) {
  const code = req.nextUrl.searchParams.get('code');
  const state = req.nextUrl.searchParams.get('state');

  // Look up session from Redis
  const session = JSON.parse(await redis.get(`session:${state}`));
  if (!session) return NextResponse.json({ error: 'Session expired' }, { status: 400 });

  // Exchange code for upstream tokens
  const tokens = await exchangeUpstreamCode(code, session.upstreamVerifier);

  // Store upstream tokens in Redis (30 day TTL)
  const userId = crypto.randomBytes(16).toString('hex');
  await redis.set(`user:${userId}:tokens`, JSON.stringify(tokens), { ex: 2592000 });

  // Generate our auth code for the MCP client
  const mcpAuthCode = crypto.randomBytes(16).toString('hex');
  await redis.set(`auth_code:${mcpAuthCode}`, userId, { ex: 300 });

  // Clean up and redirect back to MCP client
  await redis.del(`session:${state}`);
  const redirect = new URL(session.redirectUri);
  redirect.searchParams.set('code', mcpAuthCode);
  redirect.searchParams.set('state', session.state);
  return NextResponse.redirect(redirect.toString());
}

6. Token Exchange

app/api/token/route.ts:

export async function POST(req: NextRequest) {
  const body = Object.fromEntries(await req.formData());

  if (body.grant_type === 'authorization_code') {
    const userId = await redis.get(`auth_code:${body.code}`);
    if (!userId) return NextResponse.json({ error: 'invalid_grant' }, { status: 400 });
    await redis.del(`auth_code:${body.code}`);

    const accessToken = crypto.randomBytes(16).toString('hex');
    const refreshToken = crypto.randomBytes(16).toString('hex');
    await redis.set(`mcp_token:${accessToken}`, userId, { ex: 86400 });
    await redis.set(`refresh:${refreshToken}`, userId, { ex: 2592000 });

    return NextResponse.json({
      access_token: accessToken,
      token_type: 'Bearer',
      expires_in: 86400,
      refresh_token: refreshToken,
    });
  }

  if (body.grant_type === 'refresh_token') {
    const userId = await redis.get(`refresh:${body.refresh_token}`);
    if (!userId) return NextResponse.json({ error: 'invalid_grant' }, { status: 400 });

    // Optionally refresh upstream tokens here too
    const newAccess = crypto.randomBytes(16).toString('hex');
    const newRefresh = crypto.randomBytes(16).toString('hex');
    await redis.set(`mcp_token:${newAccess}`, userId, { ex: 86400 });
    await redis.set(`refresh:${newRefresh}`, userId, { ex: 2592000 });

    return NextResponse.json({
      access_token: newAccess,
      token_type: 'Bearer',
      expires_in: 86400,
      refresh_token: newRefresh,
    });
  }

  return NextResponse.json({ error: 'unsupported_grant_type' }, { status: 400 });
}

Wrapping the MCP handler

Use withMcpAuth from mcp-handler to enforce auth on tool calls while allowing unauthenticated discovery:

import { createMcpHandler, withMcpAuth } from 'mcp-handler';
import type { AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types.js';

const mcpHandler = createMcpHandler(/* ... */);

const verifyToken = async (_req: Request, bearerToken?: string): Promise<AuthInfo | undefined> => {
  if (!bearerToken) return undefined;
  const userId = await redis.get(`mcp_token:${bearerToken}`);
  if (!userId) return undefined;
  return { token: bearerToken, clientId: 'my-server', scopes: [], extra: { userId } };
};

// required: false allows initialize/tools/list without auth
// Tools check auth themselves via extra.authInfo
const handler = withMcpAuth(mcpHandler, verifyToken, {
  required: false,
  resourceUrl: SITE_URL,
});

Setting required: false is important — it allows MCP clients to discover tools without authenticating first. Auth is enforced at the tool level when the tool tries to access user data.

Redis token storage schema

KeyValueTTL
session:<id>OAuth session (redirect_uri, state, PKCE)10 min
auth_code:<code>user ID5 min
user:<id>:tokensupstream access/refresh tokens30 days
mcp_token:<token>user ID24 hours
refresh:<token>user ID30 days

Redirect URI allowlist

At minimum, allow these hostnames in your /api/authorize validation:

  • claude.ai — Claude web
  • claude.com — Claude web (alternate)
  • api.smithery.ai — Smithery scanning
  • localhost / 127.0.0.1 — local development

Add more as needed for other MCP clients. Keep the validation hostname-based (not exact URL match) because clients may use different callback paths.

Token storage with Upstash Redis

npm install @upstash/redis
import { Redis } from '@upstash/redis';
const redis = new Redis({
  url: process.env.KV_REST_API_URL!,
  token: process.env.KV_REST_API_TOKEN!,
});

Set up Upstash via Vercel Marketplace: Project Settings → Storage → Create → Upstash Redis. The env vars are automatically added to your project.

适合场景

01

OpenClaw 用户查找和安装 Skill 时

02

用户想查找某类 Agent Skill 时

03

需要根据任务场景推荐可安装能力包时

04

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

OpenClaw

87.35%
按下载量换算1,873

安全审计

VirusTotal

通过

ClawScan

可疑

Static analysis

通过

权限和风险

敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在 warning/failed 结果,不能写成本站确认安全。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills