Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

App-check use with angular fire #2858

Closed
febg11 opened this issue Jun 9, 2021 · 32 comments
Closed

App-check use with angular fire #2858

febg11 opened this issue Jun 9, 2021 · 32 comments

Comments

@febg11
Copy link

febg11 commented Jun 9, 2021

Hi

I am trying to use firebase app check with my angular project. The docs say you need to do this

Add the following initialization code to your application, before you access any Firebase services

firebase.initializeApp({
  // Your firebase configuration object
});

const appCheck = firebase.appCheck();
// Pass your reCAPTCHA v3 site key (public key) to activate(). Make sure this
// key is the counterpart to the secret key you set in the Firebase console.
appCheck.activate('abcdefghijklmnopqrstuvwxy-1234567890abcd');

I cant seem to find an easy way of doing this. I have tried using APP_INITIALIZER AND accessing the native firebase js obect using declare var but neither have worked/

I am using angularfire 6.1.5

I am not even sure how to access it. I have also tried importing the newest version of the native firebase js library. This also didnt work.

Sorry if this doesnt meet the criteria its just so new and app-check is so vague nothing comes up when i search for it.

Any help is greatly appreciated

@google-oss-bot
Copy link

This issue does not seem to follow the issue template. Make sure you provide all the required information.

@febg11
Copy link
Author

febg11 commented Jun 9, 2021

Version info

Angular:
10.2.5

Firebase:
8.6.0

AngularFire:
6.1.5

@felicksLindgren
Copy link

Was just starting to look at this feature as well. Searched a bit in the code and I feel it shouldn't be to hard to implement a extra field for security_token inside firebaseConfig and then reference it here:

const app = (existingApp || zone.runOutsideAngular(() => firebase.initializeApp(options, config as any))) as FirebaseApp;

Just check if token exists then do appCheck otherwise keep going as before.

Maybe I'm way off here, I'm not sure.

@febg11
Copy link
Author

febg11 commented Jun 27, 2021

It would also be really useful to have an input for the

<script>self.FIREBASE_APPCHECK_DEBUG_TOKEN = true;</script>

That we could set in the environment.ts along with the recaptcha key

@abierbaum
Copy link

Has anyone found a way to get appcheck working inside an existing angularfire based application?

@febg11
Copy link
Author

febg11 commented Jul 3, 2021

@abierbaum https://stackoverflow.com/questions/67908846/how-to-initialise-firebase-app-check-in-angular/67976943#67976943

Still seems super hacky as you seem to end up with 2 firebase apps.. It should really go through forRoot

@gongevangen
Copy link

https://stackoverflow.com/questions/67908846/how-to-initialise-firebase-app-check-in-angular/67976943#67976943 didn't work for me. Also I found that this feature turned it self off in the firebase console after a day, so maybe it's not really ready yet? Anyway I would love to implement it for my app, so I think Angular should implement support for it.

@alexookah
Copy link

any news about it?

@jjgriff93
Copy link

Also facing issues with this, would be great to see integration into the AngularFire library to account for app check

@jamesdaniels
Copy link
Member

Addressing in #2940

@jamesdaniels
Copy link
Member

Added in 7.1.0-rc.0

@MisterMunchkin
Copy link

Hi I've been following this issue because I wanted to add ReCaptchaV3 to my existing firebase app. I updated my @angular/fire to 7.1.0-rc.0 and firebase to 9.1.0 and fixed the compat stuff when upgrading but I get these errors:

Error: node_modules/@firebase/app-check/dist/app-check-public.d.ts:87:22 - error TS2420: Class 'CustomProvider' incorrectly implements interface 'AppCheckProvider'.
Type 'CustomProvider' is missing the following properties from type 'AppCheckProvider': getToken, initialize

87 export declare class CustomProvider implements AppCheckProvider {
~~~~~~~~~~~~~~

Error: node_modules/@firebase/app-check/dist/app-check-public.d.ts:171:22 - error TS2420: Class 'ReCaptchaV3Provider' incorrectly implements interface 'AppCheckProvider'.
Type 'ReCaptchaV3Provider' is missing the following properties from type 'AppCheckProvider': getToken, initialize

171 export declare class ReCaptchaV3Provider implements AppCheckProvider {

Version Info

Angular:
12.2.0

firebase:
9.1.0

AngularFire:
7.1.0-rc.0

@jamesdaniels
Copy link
Member

How are you importing things? I've seen reports of similar issues, mostly when folk import from [at]firebase/, you should import from [at]angular/fire/ when using with Angular.

@jamesdaniels
Copy link
Member

Here's my sample use, app.browser.module.ts app.server.module.ts

@kubanm3
Copy link

kubanm3 commented Oct 4, 2021

Have the same problem as MisterMunchkin. Angular is in strict mode. Maybe that's the problem.

@jamesdaniels
Copy link
Member

A fix for the typing problems has been merged, firebase/firebase-js-sdk#5569 and will be out in the next JS SDK release.

@naveedahmed1
Copy link

@jamesdaniels can you please also guide how to use it in Angular App?

I have added below imports:

import { provideAppCheck, initializeAppCheck, ReCaptchaV3Provider } from '@angular/fire/app-check';

@NgModule({
  imports: [
    ....
    AngularFireModule.initializeApp({ 
    //my config
     }),
    provideAppCheck(() => {
      const provider = new ReCaptchaV3Provider(myKey);
      return initializeAppCheck(undefined, { provider, isTokenAutoRefreshEnabled: true });
    }),

In my component I have:

import { getToken, AppCheck, ReCaptchaV3Provider } from '@angular/fire/app-check';

constructor(
    private appCheck: AppCheck

  ) { }

  ngOnInit() {

    getToken(this.appCheck).then((token) => {
      console.log('token', token);
    });
}

But receiving this error:

ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(t)[t -> ut -> InjectionToken angularfire2.app-check-instances -> [object Object] -> S -> S -> S -> S -> S]: 
  NullInjectorError: No provider for S!
NullInjectorError: R3InjectorError(t)[t -> ut -> InjectionToken angularfire2.app-check-instances -> [object Object] -> S -> S -> S -> S -> S]: 
  NullInjectorError: No provider for S!

@naveedahmed1
Copy link

To get rid of this error, I added below to the providers (I am not sure if this is the right way):

providers: [
    {
      provide: FIREBASE_OPTIONS, useValue: {
        //firebase config
      } }
  ]

Although I am able to receive token but probably its not valid and I am receiving this error:

CAPTCHA_CHECK_FAILED : Recaptcha verification failed - MALFORMED

@Mashsquare
Copy link

Mashsquare commented May 27, 2022

Hi,
I am using the angular fire 7.3 (modular) and is really unclear how to setup Appcheck. I am gettin a "Missing or insufficient permissions." error and as I immagined Appcheck is blocking all calls for storage and firestore.

I have seen the code sample here
and have configure the enviroment variables like shown here
I have configured the app module similarly to how you did here, except that I am not using emulators

but it still acts as if the initialization didn't go through for what concerns Appcheck, both locally and on the deployed version. (both localhost and the domain have been regisred on recaptcha)

Obviously the recaptcha V3 site key I used is correct and has been setup on firebase as well.

...What am I missing?

Version Info:

Anglular 13.1
Firebase 9.8
AngularFire 7.3

@gaurangdave
Copy link

hey @Mashsquare I am facing the same issue. Were you able to resolve yours? I also tried to use firebase debug tokens but get the same error.

@Mashsquare
Copy link

@gaurangdave Actually someone on stack overflow has been so kind to come to the rescue: https://stackoverflow.com/questions/72414785/angularfire-appcheck-not-initialized-correctly

The sample code you can find in the documentation ENTIRELY SKIPS the part where you are supposed to initialize the appcheck in the app-module, you can find the full answer in the link I gave you. It worked for me and when runnig locally it shows a debug token in the console which luckily does not show up in production when you deploy

@naveedahmed1
Copy link

naveedahmed1 commented Jun 3, 2022

@Mashsquare were you able to verify the generated token on backend in production?

I had the exact same setup but it never worked. Actually in dev environment i.e. with debug token, I believe no verification is done.

I posted the same question on Stackoverflow https://stackoverflow.com/questions/72308016/angular-firebase-app-check-recaptcha-recaptcha-enterprise-for-phone-verifica

I ended up generating token using ng-recaptcha which works fine.

@Mashsquare
Copy link

@naveedahmed1 it is my understanding that when using debug token appcheck allows you to access your APIs in conditions where it should've refused the access but of course such debug token must be registered in the console as the docs say here: https://firebase.google.com/docs/app-check/web/debug-provider so yes it is "normal" that when those conditions are met no verification is done...

In my case, I didn't use the phone provider but I used Google, Facebook and Twitter to let users signup and authenticate while you used the Phone Auth which might add some extra complexity I guess...?! Sorry I can't say more than this really I wish I could help more

@naveedahmed1
Copy link

Thanks @Mashsquare , have you tried you app in production? I mean without debug token?

@Mashsquare
Copy link

@naveedahmed1 yes all works as expected!

@pascalbe-dev
Copy link

@gaurangdave Actually someone on stack overflow has been so kind to come to the rescue: https://stackoverflow.com/questions/72414785/angularfire-appcheck-not-initialized-correctly

The sample code you can find in the documentation ENTIRELY SKIPS the part where you are supposed to initialize the appcheck in the app-module, you can find the full answer in the link I gave you. It worked for me and when runnig locally it shows a debug token in the console which luckily does not show up in production when you deploy

I tried this as well but got this error message in my app during start up:

NullInjectorError: R3InjectorError(AppModule)[AuthenticatedGuard -> AuthenticationAdapter -> AngularFireAuth -> AppCheckInstances -> InjectionToken angularfire2.app-check-instances -> [object Object] -> FirebaseApps -> FirebaseApps -> FirebaseApps]:
NullInjectorError: No provider for FirebaseApps!

Does anyone know how to get that resolved?

@Mashsquare
Copy link

@pascalbe-dev Hard to say, it would help to give a look at your app.module and the routing module as well (since in this error the guard is involved)

@soyaaroncervantes
Copy link

In my case, before I upgrated to 7.4, my code was working, I was using 7.3, and the way I did it working was like this

@NgModule({
  imports: [
    provideFirebaseApp(() => app()),
    provideAuth( () => auth()),
    provideAppCheck( () => appCheck()),
    provideAnalytics(() => analytics()),
    AuthGuardModule
  ]
})
export class AppFirebaseModule {}
export const app = () => initializeApp(environment.firebase);
export const auth = () => initializeAuth(app(), {
  persistence: browserSessionPersistence,
  popupRedirectResolver: browserPopupRedirectResolver,
});
export const appCheck = () => initializeAppCheck( app(), {
  provider: new ReCaptchaV3Provider(environment.recaptcha.site),
  isTokenAutoRefreshEnabled: true
});

After I upgraded it, it's throwing this error:

Component app-check has not been registered yet.

@pascalbe-dev
Copy link

pascalbe-dev commented Aug 10, 2022

@Mashsquare

@pascalbe-dev Hard to say, it would help to give a look at your app.module and the routing module as well (since in this error the guard is involved)

Sorry, it took me a while to get back to that.

My AppModule looks like that. Please note, that I'm still using the compat API to initialize the the Firebase app.

import { NgModule } from '@angular/core';
import {
  initializeAppCheck,
  provideAppCheck,
  ReCaptchaV3Provider,
} from '@angular/fire/app-check';
import { AngularFireModule } from '@angular/fire/compat';
import { BrowserModule } from '@angular/platform-browser';
import { environment } from '../environments/environment';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase),
    provideAppCheck(() =>
      initializeAppCheck(undefined, {
        provider: new ReCaptchaV3Provider(environment.recaptchaSiteKey),
        isTokenAutoRefreshEnabled: true,
      })
    ),
  ],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

Could it be, that the appCheck integration does not work with the compat API?

@dmars8047
Copy link

Is there any documentation for appcheck at all for this library? I have been searching for awhile now and I cannot find solution that works. I am using the compat API in my module and I have had a lot of problems. The one I really cant get passed is the NullInjectorError.

@pascalbe-dev
Copy link

@dmars8047
I ended up refactoring to use the modular API. Otherwise, I could not get it to work.

I think, there are samples for app check and the modular API.

@TamilselvanMariyappan
Copy link

In my case, before I upgrated to 7.4, my code was working, I was using 7.3, and the way I did it working was like this

@NgModule({
  imports: [
    provideFirebaseApp(() => app()),
    provideAuth( () => auth()),
    provideAppCheck( () => appCheck()),
    provideAnalytics(() => analytics()),
    AuthGuardModule
  ]
})
export class AppFirebaseModule {}
export const app = () => initializeApp(environment.firebase);
export const auth = () => initializeAuth(app(), {
  persistence: browserSessionPersistence,
  popupRedirectResolver: browserPopupRedirectResolver,
});
export const appCheck = () => initializeAppCheck( app(), {
  provider: new ReCaptchaV3Provider(environment.recaptcha.site),
  isTokenAutoRefreshEnabled: true
});

After I upgraded it, it's throwing this error:

Component app-check has not been registered yet.

I have same issue. Did you find solution for it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests