作为从 Firebase 迁移到 Auth0 的一部分,我的前端 Angular 应用程序根据用户的电子邮件地址有条件地对用户进行 Firebase 或 Auth0 身份验证。我正在尝试配置 Auth0 Angular SDK for SPA 提供的 Auth0 AuthHttpInterceptor,以便仅当用户已知是 Auth0 用户时(即,当他们已经登录时)才会尝试添加身份验证令牌到我的应用程序)。特别是,我希望它只是对经过 Firebase 身份验证的用户进行“直通”请求。
我已经配置了 Auth0 HttpInterceptor 和我的自定义 Firebase HttpInterceptor,以便依次调用它们。我已将 Auth0 设置为“allowAnonymous”,试图使其在当前用户未通过 Auth0 身份验证的情况下跳过处理。拦截器在我的模块中配置如下:
Auth0Module.forRoot({
// ...
httpInterceptor: {
allowedList: [
{
uri: 'http://localhost:8080/*',
// Allow API to go through even if no Auth0 authentication, in attempt
// to skip Auth0-specific processing for Firebase users.
allowAnonymous: true,
},
],
},
}),
不幸的是,Auth0 拦截器坚持在每个请求上调用 /authorize 端点(即使用户仅通过 Firebase 进行身份验证)。
我考虑过,如果我以相反的顺序链接 HttpInterceptors(首先是我的自定义拦截器,然后是 Auth0),我可能能够有条件地为 Firebase 用户跳过 Auth0 拦截器,但我找不到办法做到这一点。
HttpInterceptor 有没有办法跳过尚未执行的链式拦截器?
您可以创建一个聚合拦截器,并根据您的逻辑将其委托给 auth0 或 firebase:
export class AggregateInterceptor implements HttpInterceptor {
constructor(private auth0Ceptor: AuthHttpInterceptor,
private firebaseCeptor: FirebaseInterceptor) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (...) {
return this.auth0Ceptor.intercept(req, next);
} else {
return this.firebaseCeptor.intercept(req, next);
}
}
}
如果您希望 auth0 拦截器完成工作,但实际上并不处理请求,而是将其转发到 firebase,您可以使用自定义处理程序:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const chainHandler: HttpHandler = {
handle(req: HttpRequest<any>): Observable<HttpEvent<any>> {
return this.firebaseCeptor.intercept(req, next);
}
};
if (...) {
return this.auth0Ceptor.intercept(req, chainHandler);
} else {
return this.firebaseCeptor.intercept(req, next);
}
}
这是 @aviad P 答案的扩展版本,我在为访客用户调用 API 时收到错误“需要登录”。 如果用户登录或仅使用通用句柄方法,它将使用 auth0 拦截器。
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
// convert promise to observable using 'from' operator
return from(this.handle(request, next))
}
async handle(request: HttpRequest<any>, next: HttpHandler) {
const isAuthenticated = await firstValueFrom(this.authService.isAuthenticated$)
if (isAuthenticated){
return await lastValueFrom(this.auth0Ceptor.intercept(request, next));
}else{
return await lastValueFrom(next.handle(request));
}
}