AngularFireAuth redirect issue with angular routing guard












3















Dear stackoverflow community,



i have the following issue. I try to use FirebaseAuthentication together with Angular7 and im trying to secure routes with guards so only logged in users can for example visit the /profile url.



My login (login.component.ts) looks like this. At first I import AngularFireAuth and use it for logging in with Google, Facebook or Email. In the ngOnInit method I am subscribing to the authState so I can redirect to user. This is all working fine.



login.component.ts



In the next step I wanted to write an AuthGuard for the /profile url so only logged in users can visit their profile. The non logged in users should be redirected to /login first.



app-routing.module.ts



My AuthGuard (auth.guard.ts) looks like this and is using a class AuthService (auth.service.ts) internally. This AuthService is injected and offers a method isAuthenticated. If the user is authenticated he should be presented with his profile, otherwise the AuthGuard should return false and redirect him to login.



AuthGuard



The AuthService looks like this and its method isAuthenticated should return true if the user is logged in and false otherwise.



AuthService



If i don't add this dummy return true at the end of the function he will always redirect me back to /login also when I am logged in. He also tells me that the function has no return value



error. function needs a return value



So I know that this subscription is not enough in the isAuthenticated method but I am curious what the best solution would look like to detect if the user is logged in.



If one of you has a best practice type of solution it would be very nice if he could show me. There are not very many proper tutorials out there.



In the meantime I will try to keep looking for a solution on google. I hope someone of you can help me with this problem. Thank you :)



best regards
Jan










share|improve this question



























    3















    Dear stackoverflow community,



    i have the following issue. I try to use FirebaseAuthentication together with Angular7 and im trying to secure routes with guards so only logged in users can for example visit the /profile url.



    My login (login.component.ts) looks like this. At first I import AngularFireAuth and use it for logging in with Google, Facebook or Email. In the ngOnInit method I am subscribing to the authState so I can redirect to user. This is all working fine.



    login.component.ts



    In the next step I wanted to write an AuthGuard for the /profile url so only logged in users can visit their profile. The non logged in users should be redirected to /login first.



    app-routing.module.ts



    My AuthGuard (auth.guard.ts) looks like this and is using a class AuthService (auth.service.ts) internally. This AuthService is injected and offers a method isAuthenticated. If the user is authenticated he should be presented with his profile, otherwise the AuthGuard should return false and redirect him to login.



    AuthGuard



    The AuthService looks like this and its method isAuthenticated should return true if the user is logged in and false otherwise.



    AuthService



    If i don't add this dummy return true at the end of the function he will always redirect me back to /login also when I am logged in. He also tells me that the function has no return value



    error. function needs a return value



    So I know that this subscription is not enough in the isAuthenticated method but I am curious what the best solution would look like to detect if the user is logged in.



    If one of you has a best practice type of solution it would be very nice if he could show me. There are not very many proper tutorials out there.



    In the meantime I will try to keep looking for a solution on google. I hope someone of you can help me with this problem. Thank you :)



    best regards
    Jan










    share|improve this question

























      3












      3








      3








      Dear stackoverflow community,



      i have the following issue. I try to use FirebaseAuthentication together with Angular7 and im trying to secure routes with guards so only logged in users can for example visit the /profile url.



      My login (login.component.ts) looks like this. At first I import AngularFireAuth and use it for logging in with Google, Facebook or Email. In the ngOnInit method I am subscribing to the authState so I can redirect to user. This is all working fine.



      login.component.ts



      In the next step I wanted to write an AuthGuard for the /profile url so only logged in users can visit their profile. The non logged in users should be redirected to /login first.



      app-routing.module.ts



      My AuthGuard (auth.guard.ts) looks like this and is using a class AuthService (auth.service.ts) internally. This AuthService is injected and offers a method isAuthenticated. If the user is authenticated he should be presented with his profile, otherwise the AuthGuard should return false and redirect him to login.



      AuthGuard



      The AuthService looks like this and its method isAuthenticated should return true if the user is logged in and false otherwise.



      AuthService



      If i don't add this dummy return true at the end of the function he will always redirect me back to /login also when I am logged in. He also tells me that the function has no return value



      error. function needs a return value



      So I know that this subscription is not enough in the isAuthenticated method but I am curious what the best solution would look like to detect if the user is logged in.



      If one of you has a best practice type of solution it would be very nice if he could show me. There are not very many proper tutorials out there.



      In the meantime I will try to keep looking for a solution on google. I hope someone of you can help me with this problem. Thank you :)



      best regards
      Jan










      share|improve this question














      Dear stackoverflow community,



      i have the following issue. I try to use FirebaseAuthentication together with Angular7 and im trying to secure routes with guards so only logged in users can for example visit the /profile url.



      My login (login.component.ts) looks like this. At first I import AngularFireAuth and use it for logging in with Google, Facebook or Email. In the ngOnInit method I am subscribing to the authState so I can redirect to user. This is all working fine.



      login.component.ts



      In the next step I wanted to write an AuthGuard for the /profile url so only logged in users can visit their profile. The non logged in users should be redirected to /login first.



      app-routing.module.ts



      My AuthGuard (auth.guard.ts) looks like this and is using a class AuthService (auth.service.ts) internally. This AuthService is injected and offers a method isAuthenticated. If the user is authenticated he should be presented with his profile, otherwise the AuthGuard should return false and redirect him to login.



      AuthGuard



      The AuthService looks like this and its method isAuthenticated should return true if the user is logged in and false otherwise.



      AuthService



      If i don't add this dummy return true at the end of the function he will always redirect me back to /login also when I am logged in. He also tells me that the function has no return value



      error. function needs a return value



      So I know that this subscription is not enough in the isAuthenticated method but I am curious what the best solution would look like to detect if the user is logged in.



      If one of you has a best practice type of solution it would be very nice if he could show me. There are not very many proper tutorials out there.



      In the meantime I will try to keep looking for a solution on google. I hope someone of you can help me with this problem. Thank you :)



      best regards
      Jan







      angular firebase firebase-authentication angular-router-guards






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Dec 28 '18 at 14:19









      Jan KreischerJan Kreischer

      708




      708
























          2 Answers
          2






          active

          oldest

          votes


















          2














          subscription cannot return value.



          you can use map instead of subscribe.



          return this.afAuth.authState.pipe(map((res) => {
          if (res && res.uid)
          return true;

          return false;
          });


          also change the return value signature of isAuthenticated Method from boolean to Observable<boolean> or Observable<boolean> | boolean






          share|improve this answer
























          • Thanks a lot, this solved my problem :)

            – Jan Kreischer
            Dec 29 '18 at 20:24



















          2














          I already used Angular FireAuth to implement the same thing as yours and here is what I came up with:
          Function isAuthenticated ie isLoggedIn



          public isLoggedIn() {
          return this.afAuth.authState.pipe(first()).toPromise();
          }


          And in my guard:

          auth.guard.ts



          canActivate (next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
          return this.auth.isLoggedIn().then((value) => {
          if (value) {
          return true;
          } else {
          this.router.navigate(['./login']);
          return false;
          }
          });
          }


          Hope it will help you ;)




          EDIT

          I used those tutorials to better understand how to use AngularFireAuth:
          https://angularfirebase.com/tag/authentication/


          And in your case, you have this one:
          https://angularfirebase.com/lessons/router-guards-to-redirect-unauthorized-firebase-users/






          share|improve this answer

























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53959947%2fangularfireauth-redirect-issue-with-angular-routing-guard%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            2














            subscription cannot return value.



            you can use map instead of subscribe.



            return this.afAuth.authState.pipe(map((res) => {
            if (res && res.uid)
            return true;

            return false;
            });


            also change the return value signature of isAuthenticated Method from boolean to Observable<boolean> or Observable<boolean> | boolean






            share|improve this answer
























            • Thanks a lot, this solved my problem :)

              – Jan Kreischer
              Dec 29 '18 at 20:24
















            2














            subscription cannot return value.



            you can use map instead of subscribe.



            return this.afAuth.authState.pipe(map((res) => {
            if (res && res.uid)
            return true;

            return false;
            });


            also change the return value signature of isAuthenticated Method from boolean to Observable<boolean> or Observable<boolean> | boolean






            share|improve this answer
























            • Thanks a lot, this solved my problem :)

              – Jan Kreischer
              Dec 29 '18 at 20:24














            2












            2








            2







            subscription cannot return value.



            you can use map instead of subscribe.



            return this.afAuth.authState.pipe(map((res) => {
            if (res && res.uid)
            return true;

            return false;
            });


            also change the return value signature of isAuthenticated Method from boolean to Observable<boolean> or Observable<boolean> | boolean






            share|improve this answer













            subscription cannot return value.



            you can use map instead of subscribe.



            return this.afAuth.authState.pipe(map((res) => {
            if (res && res.uid)
            return true;

            return false;
            });


            also change the return value signature of isAuthenticated Method from boolean to Observable<boolean> or Observable<boolean> | boolean







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Dec 28 '18 at 14:25









            SimonareSimonare

            7,18611435




            7,18611435













            • Thanks a lot, this solved my problem :)

              – Jan Kreischer
              Dec 29 '18 at 20:24



















            • Thanks a lot, this solved my problem :)

              – Jan Kreischer
              Dec 29 '18 at 20:24

















            Thanks a lot, this solved my problem :)

            – Jan Kreischer
            Dec 29 '18 at 20:24





            Thanks a lot, this solved my problem :)

            – Jan Kreischer
            Dec 29 '18 at 20:24













            2














            I already used Angular FireAuth to implement the same thing as yours and here is what I came up with:
            Function isAuthenticated ie isLoggedIn



            public isLoggedIn() {
            return this.afAuth.authState.pipe(first()).toPromise();
            }


            And in my guard:

            auth.guard.ts



            canActivate (next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
            return this.auth.isLoggedIn().then((value) => {
            if (value) {
            return true;
            } else {
            this.router.navigate(['./login']);
            return false;
            }
            });
            }


            Hope it will help you ;)




            EDIT

            I used those tutorials to better understand how to use AngularFireAuth:
            https://angularfirebase.com/tag/authentication/


            And in your case, you have this one:
            https://angularfirebase.com/lessons/router-guards-to-redirect-unauthorized-firebase-users/






            share|improve this answer






























              2














              I already used Angular FireAuth to implement the same thing as yours and here is what I came up with:
              Function isAuthenticated ie isLoggedIn



              public isLoggedIn() {
              return this.afAuth.authState.pipe(first()).toPromise();
              }


              And in my guard:

              auth.guard.ts



              canActivate (next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
              return this.auth.isLoggedIn().then((value) => {
              if (value) {
              return true;
              } else {
              this.router.navigate(['./login']);
              return false;
              }
              });
              }


              Hope it will help you ;)




              EDIT

              I used those tutorials to better understand how to use AngularFireAuth:
              https://angularfirebase.com/tag/authentication/


              And in your case, you have this one:
              https://angularfirebase.com/lessons/router-guards-to-redirect-unauthorized-firebase-users/






              share|improve this answer




























                2












                2








                2







                I already used Angular FireAuth to implement the same thing as yours and here is what I came up with:
                Function isAuthenticated ie isLoggedIn



                public isLoggedIn() {
                return this.afAuth.authState.pipe(first()).toPromise();
                }


                And in my guard:

                auth.guard.ts



                canActivate (next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
                return this.auth.isLoggedIn().then((value) => {
                if (value) {
                return true;
                } else {
                this.router.navigate(['./login']);
                return false;
                }
                });
                }


                Hope it will help you ;)




                EDIT

                I used those tutorials to better understand how to use AngularFireAuth:
                https://angularfirebase.com/tag/authentication/


                And in your case, you have this one:
                https://angularfirebase.com/lessons/router-guards-to-redirect-unauthorized-firebase-users/






                share|improve this answer















                I already used Angular FireAuth to implement the same thing as yours and here is what I came up with:
                Function isAuthenticated ie isLoggedIn



                public isLoggedIn() {
                return this.afAuth.authState.pipe(first()).toPromise();
                }


                And in my guard:

                auth.guard.ts



                canActivate (next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
                return this.auth.isLoggedIn().then((value) => {
                if (value) {
                return true;
                } else {
                this.router.navigate(['./login']);
                return false;
                }
                });
                }


                Hope it will help you ;)




                EDIT

                I used those tutorials to better understand how to use AngularFireAuth:
                https://angularfirebase.com/tag/authentication/


                And in your case, you have this one:
                https://angularfirebase.com/lessons/router-guards-to-redirect-unauthorized-firebase-users/







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Dec 28 '18 at 14:56

























                answered Dec 28 '18 at 14:41









                Ben ThieBen Thie

                1165




                1165






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53959947%2fangularfireauth-redirect-issue-with-angular-routing-guard%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Mossoró

                    Error while reading .h5 file using the rhdf5 package in R

                    Pushsharp Apns notification error: 'InvalidToken'