如何从SPA客户端在Azure中使用Easy Auth实现程序化认证?
Azure Function Easy Auth 在JS/TS SPA中的程序化认证方案
浏览器直接访问能通过Cookie完成认证,但用fetch等工具请求时返回401,核心原因是JS请求默认不会自动携带Cookie,加上可能的CORS配置问题,以下是针对Svelte/React/Vue等SPA的具体解决步骤:
1. 强制请求携带认证Cookie
不管用原生fetch还是axios等HTTP库,必须显式配置凭证传递选项:
- 原生fetch示例:
// 同源场景(SPA和Function同域名) fetch('/.auth/me', { credentials: 'same-origin' }) .then(res => res.json()) .then(user => { // 处理用户信息 console.log('当前用户:', user); }) .catch(err => console.error('认证请求失败:', err)); // 跨域场景(SPA部署在独立域名) fetch('https://example.com/.auth/me', { credentials: 'include' }) .then(res => res.json()) .then(user => console.log('当前用户:', user)) .catch(err => console.error('认证请求失败:', err)); - axios示例:
axios.get('https://example.com/.auth/me', { withCredentials: true }) .then(res => console.log('当前用户:', res.data)) .catch(err => console.error('认证请求失败:', err));
2. 配置Azure端的CORS规则
如果SPA和Function不同域名,必须在Azure Function的平台设置中完成两项配置:
- 将SPA的完整域名加入允许的来源列表
- 勾选允许凭据选项(否则浏览器会拦截跨域请求的Cookie传递)
3. 程序化触发登录流程
要在SPA中主动引导用户登录,需配合Easy Auth的回调机制:
- 在Azure Easy Auth的AAD配置里,把SPA的登录回调页面(比如
https://your-spa.com/login-callback)加入回复URL列表 - 在SPA中,通过跳转链接触发登录,指定登录完成后的回调地址:
const handleLogin = () => { window.location.href = 'https://example.com/.auth/login/aad?post_login_redirect_uri=https://your-spa.com/login-callback'; }; - 在回调页面中,调用
/.auth/me接口获取用户信息(此时Cookie已由浏览器保存,加上凭证配置即可成功请求)
4. 初始化时自动检查认证状态
可以在SPA的根组件挂载时,自动检查用户是否已登录:
- React示例:
import { useEffect, useState } from 'react'; function App() { const [user, setUser] = useState(null); useEffect(() => { const checkAuthStatus = async () => { try { const res = await fetch('https://example.com/.auth/me', { credentials: 'include' }); if (res.ok) { const userData = await res.json(); setUser(userData); } else { // 未登录,引导至登录流程 window.location.href = 'https://example.com/.auth/login/aad?post_login_redirect_uri=https://your-spa.com'; } } catch (err) { console.error('认证状态检查失败:', err); } }; checkAuthStatus(); }, []); return ( <div> {user ? ( <div>欢迎,{user.clientPrincipal.name}</div> ) : ( <button onClick={handleLogin}>登录</button> )} </div> ); } - Svelte/Vue的逻辑类似,在组件的
onMount/mounted钩子中执行相同的检查逻辑
5. 程序化登出
通过跳转至Easy Auth的登出接口,并指定登出后的跳转地址:
const handleLogout = () => { window.location.href = 'https://example.com/.auth/logout?post_logout_redirect_uri=https://your-spa.com'; };
内容的提问来源于stack exchange,提问作者Techlead
相关产品推荐
相关产品推荐

