您也可以使用服务和拦截器(下面的代码)来实现这一点。该服务可能应该添加某种类型的令牌缓存(更短的 TTL 以提高安全性,更长的 TTL 以降低成本)。有关更多详细信息,请参阅在 Web 应用程序中使用 reCAPTCHA Enterprise 启用应用程序检查。
为了使服务实现简单,不包括令牌缓存代码。
该服务包含使用 App Check 获取令牌的逻辑。
import { Injectable } from '@angular/core';
import { FirebaseApp, initializeApp } from 'firebase/app';
import { AppCheck, AppCheckTokenResult, getToken, initializeAppCheck, ReCaptchaEnterpriseProvider } from 'firebase/app-check';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root'
})
export class AppCheckService {
app: FirebaseApp;
appCheck: AppCheck;
constructor() {
this.app = initializeApp(environment.firebase);
// Create a ReCaptchaEnterpriseProvider instance using reCAPTCHA Enterprise.
this.appCheck = initializeAppCheck(this.app, {
provider: new ReCaptchaEnterpriseProvider(environment.recaptchaEnterpriseKey),
isTokenAutoRefreshEnabled: true // Set to true to allow auto-refresh.
});
}
async getToken(): Promise<AppCheckTokenResult | undefined> {
let appCheckTokenResponse;
try {
appCheckTokenResponse = await getToken(this.appCheck);
} catch (err) {
// TODO: Handle any errors if the token was not retrieved.
return;
}
return appCheckTokenResponse;
}
}
然后,该服务可以由负责添加X-Firebase-AppCheck
带有令牌的 HTTP 标头的拦截器使用。
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { AppCheckTokenResult } from '@firebase/app-check';
import { from, Observable } from 'rxjs';
import { switchMap, take } from 'rxjs/operators';
import { environment } from '../../environments/environment';
import { AppCheckService } from '../services/app-check.service';
@Injectable()
export class AppCheckInterceptor implements HttpInterceptor {
constructor(private readonly appCheckService: AppCheckService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return from(this.appCheckService.getToken()).pipe(
take(1), // See https://stackoverflow.com/a/60196923/828547.
switchMap((token: AppCheckTokenResult | undefined) => {
if (token) {
request = request.clone({
setHeaders: { "X-Firebase-AppCheck": token?.token },
});
}
return next.handle(request);
}),
);
}
}
您将需要添加recaptchaEnterpriseKey
到您的 Angular 环境文件中
export const environment = {
recaptchaEnterpriseKey: '6LfGni324khkjh324hkDSFsdfSfsdm',
};
最后将拦截器添加到您的app.module.ts
文件中
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AppCheckInterceptor,
multi: true,
},
]