返回顶部
a

azure-authAzure认证

|

作者: admin | 来源: ClawHub
源自
ClawHub
版本
V 0.1.0
安全检测
已通过
1,465
下载量
免费
免费
1
收藏
概述
安装方式
版本历史

azure-auth

Azure Auth - 用于 React + Cloudflare Workers 的 Microsoft Entra ID

包版本: @azure/msal-react@5.0.2, @azure/msal-browser@5.0.2, jose@6.1.3
重大变更: MSAL v4→v5 迁移(2026年1月),Azure AD B2C 停用(2025年5月 - 新注册已阻止,现有用户可使用至2030年),ADAL 退役(2025年9月 - 已完成)
最后更新: 2026-01-21



架构概览

┌─────────────────────┐ ┌──────────────────────┐ ┌─────────────────────┐
│ React SPA │────▶│ Microsoft Entra ID │────▶│ Cloudflare Worker │
│ @azure/msal-react │ │ (login.microsoft) │ │ jose JWT 验证 │
└─────────────────────┘ └──────────────────────┘ └─────────────────────┘
│ │
│ 授权码 + PKCE │
│ (accesstoken, idtoken) │
└──────────────────────────────────────────────────────────┘
授权头中的 Bearer 令牌

关键约束: MSAL.js 在 Cloudflare Workers 中无法运行(依赖浏览器/Node.js API)。请使用 jose 库进行后端令牌验证。



快速开始

1. 安装依赖

bash

前端 (React SPA)


npm install @azure/msal-react @azure/msal-browser

后端 (Cloudflare Workers)

npm install jose

2. Azure 门户设置

  1. 1. 前往 Microsoft Entra ID应用注册新注册
  2. 重定向 URI 设置为 http://localhost:5173(SPA 类型)
  3. 记下 应用程序(客户端)ID目录(租户)ID
  4. 身份验证 下:
- 启用 访问令牌ID 令牌 - 添加生产环境重定向 URI
  1. 5. 在 API 权限 下:
- 添加 User.Read(Microsoft Graph) - 如有需要,授予管理员同意

前端:MSAL React 设置

配置 (src/auth/msal-config.ts)

typescript
import { Configuration, LogLevel } from @azure/msal-browser;

export const msalConfig: Configuration = {
auth: {
clientId: import.meta.env.VITEAZURECLIENT_ID,
authority: https://login.microsoftonline.com/${import.meta.env.VITEAZURETENANT_ID},
redirectUri: window.location.origin,
postLogoutRedirectUri: window.location.origin,
navigateToLoginRequestUrl: true,
},
cache: {
cacheLocation: localStorage, // 或 sessionStorage
storeAuthStateInCookie: true, // 解决 Safari/Edge 问题所需
},
system: {
loggerOptions: {
logLevel: LogLevel.Warning,
loggerCallback: (level, message) => {
if (level === LogLevel.Error) console.error(message);
},
},
},
};

// 令牌请求的作用域
export const loginRequest = {
scopes: [User.Read, openid, profile, email],
};

// API 调用的作用域(在此处添加您的 API 作用域)
export const apiRequest = {
scopes: [api://${import.meta.env.VITEAZURECLIENTID}/accessas_user],
};

MsalProvider 设置 (src/main.tsx)

typescript
import React from react;
import ReactDOM from react-dom/client;
import { PublicClientApplication, EventType } from @azure/msal-browser;
import { MsalProvider } from @azure/msal-react;
import { msalConfig } from ./auth/msal-config;
import App from ./App;

// 关键:在组件树外部初始化 MSAL,防止重复实例化
const msalInstance = new PublicClientApplication(msalConfig);

// 处理页面加载时的重定向 promise
msalInstance.initialize().then(() => {
// 重定向后设置活动账户
// 重要:使用 getAllAccounts()(返回数组),而不是 getActiveAccount()(返回单个账户或 null)
const accounts = msalInstance.getAllAccounts();
if (accounts.length > 0) {
msalInstance.setActiveAccount(accounts[0]);
}

// 监听登录事件
msalInstance.addEventCallback((event) => {
if (event.eventType === EventType.LOGIN_SUCCESS && event.payload) {
const account = (event.payload as { account: any }).account;
msalInstance.setActiveAccount(account);
}
});

ReactDOM.createRoot(document.getElementById(root)!).render(





);
});

受保护路由组件

typescript
import { useMsal, useIsAuthenticated } from @azure/msal-react;
import { InteractionStatus } from @azure/msal-browser;
import { loginRequest } from ./msal-config;

export function ProtectedRoute({ children }: { children: React.ReactNode }) {
const { instance, inProgress } = useMsal();
const isAuthenticated = useIsAuthenticated();

// 等待 MSAL 完成任何正在进行的操作
if (inProgress !== InteractionStatus.None) {
return

加载中...
;
}

if (!isAuthenticated) {
// 触发登录重定向
instance.loginRedirect(loginRequest);
return

正在重定向到登录页面...
;
}

return <>{children};
}

获取 API 调用令牌

typescript
import { useMsal } from @azure/msal-react;
import { InteractionRequiredAuthError } from @azure/msal-browser;
import { apiRequest } from ./msal-config;

export function useApiToken() {
const { instance, accounts } = useMsal();

async function getAccessToken(): Promise {
if (accounts.length === 0) return null;

const request = {
...apiRequest,
account: accounts[0],
};

try {
// 首先尝试静默获取令牌
const response = await instance.acquireTokenSilent(request);
return response.accessToken;
} catch (error) {
if (error instanceof InteractionRequiredAuthError) {
// 静默获取失败,需要交互式登录
// 这处理过期的刷新令牌 (AADSTS700084)
await instance.acquireTokenRedirect(request);
return null;
}
throw error;
}
}

return { getAccessToken };
}



后端:Cloudflare Workers JWT 验证

为什么使用 jose 而不是 MSAL

MSAL.js 依赖浏览器 API(localStorage、sessionStorage)和 Node.js 加密模块,这些在 Cloudflare Workers 的 V8 隔离运行时中不存在。jose 库是纯 JavaScript,可以在 Workers 中完美运行。

JWT 验证 (src/auth/validate-token.ts)

typescript
import * as jose from jose;

interface EntraTokenPayload {
aud: string; // 受众(您的客户端 ID 或 API URI)
iss: string; // 颁发者(https://login.microsoftonline.com/{tenant}/v2.0)
sub: string; // 主题(用户的唯一 ID)
oid: string; // 对象 ID(用户的 Azure AD 对象 ID)
preferred_username: string;
name: string;
email?: string;
roles?: string[]; // 如果配置了应用角色
scp?: string; // 作用域(空格分隔)
}

// 缓存 JWKS,避免每次请求都获取
let jwksCache: jose.JWTVerifyGetKey | null = null;
let jwksCacheTime = 0;
const JWKSCACHEDURATION = 3600000; // 1 小时

async function getJWKS(tenantId: string): Promise {
const now = Date.now();

if (jwksCache && now - jwksCacheTime < JWKSCACHEDURATION) {
return jwksCache;
}

// 关键:Azure AD JWKS 不在 .well-known/jwks.json 路径
// 必须首先从 openid-configuration 获取
const configUrl = https://login.microsoftonline.com/${tenantId}/v2.0/.well-known/openid-configuration;
const configResponse = await fetch(configUrl);
const config = await configResponse.json()

标签

skill ai

通过对话安装

该技能支持在以下平台通过对话安装:

OpenClaw WorkBuddy QClaw Kimi Claude

方式一:安装 SkillHub 和技能

帮我安装 SkillHub 和 azure-auth-1776376063 技能

方式二:设置 SkillHub 为优先技能安装源

设置 SkillHub 为我的优先技能安装源,然后帮我安装 azure-auth-1776376063 技能

通过命令行安装

skillhub install azure-auth-1776376063

下载

⬇ 下载 azure-auth v0.1.0(免费)

文件大小: 24.43 KB | 发布时间: 2026-4-17 13:53

v0.1.0 最新 2026-4-17 13:53
azure-auth 0.1.0

- Initial release providing Microsoft Entra ID (Azure AD) authentication for React SPAs and JWT validation in Cloudflare Workers.
- Implements Authorization Code Flow with PKCE using @azure/msal-react v5 and the jose library (Cloudflare Workers compatible).
- Offers mitigation guidance for 8 common MSAL/Azure AD errors, including SSO issues and token refresh problems.
- Includes quick-start setup for both frontend (React) and backend (Cloudflare Workers).
- Documents key breaking changes: MSAL v4→v5 migration, Azure AD B2C and ADAL retirements.
- Provides step-by-step configuration, recommended patterns, and architecture overview.

Archiver·手机版·闲社网·闲社论坛·羊毛社区· 多链控股集团有限公司 · 苏ICP备2025199260号-1

Powered by Discuz! X5.0   © 2024-2025 闲社网·线报更新论坛·羊毛分享社区·http://xianshe.com

p2p_official_large
返回顶部