我有一个站点,该站点具有基于Web组件的体系结构,其中每个Web组件都可以是单独的Vue应用程序,其自己的API层通过Axios集成。我需要为来自根应用程序或Web组件应用程序的所有HTTP请求实现身份验证中间件。我不能使用Axios内置的拦截器机制,因为将有多个Axios实例。有什么办法可以使用全局JS方法吗?我知道那里有some browser extension based API,但这似乎不是我想要的东西。
答案 0 :(得分:0)
只要其他人有兴趣,我都可以通过服务人员解决。您可以订阅fetch
事件,并根据您的身份验证逻辑进行响应。您的服务人员代码如下所示:
self.addEventListener('fetch', async (event) => {
const isAuthorised = await checkIsAuthorized(); // your auth API layer
if (!isAuthorised) {
const response = new Response(null, {
status: 401,
statusText: 'Unauthorised',
});
event.respondWith(response);
return;
}
event.respondWith(fetch(event.request));
});
Service Worker也能够拦截来自影子DOM的axios请求,因此非常适合Web组件案例。
此外,还有一个nice article by Bartosz Polnik关于使用服务工作者实现身份验证层。