简体   繁体   English

Angular Firebase Routeguard 身份验证

[英]Angular Firebase Routeguard Authentication

I am actually learning Angular and firebase, I want to add a route guard to users dashboard so that only logged in users can view the page.我实际上正在学习 Angular 和 firebase,我想向用户仪表板添加一个路由保护,以便只有登录的用户才能查看该页面。 The Authentication works fine but I am having issues restricting none logged in users to access users dashboard This is my code below.身份验证工作正常,但我在限制没有登录的用户访问用户仪表板时遇到问题这是我的代码如下。

Authservice.service.ts Authservice.service.ts

@Injectable({
      providedIn: 'root'
    })
    export class AuthServiceService {

      newUser: any;
      // passing Error message
      private eventAuthError = new BehaviorSubject<string>('');
      eventError$ = this.eventAuthError.asObservable();
      showSuccessCreated: boolean;

      constructor( private authz: AngularFireAuth, private db: AngularFirestore, private route:Router) 
      { } 
      // geting user details
      getUserState() {
       return this.authz.authState;
      }

      // LoggIn Users
      login(email: string , password: string ) {
        this.authz.auth.signInWithEmailAndPassword(email, password)
        .catch( error => {
          this.eventAuthError.next(error);
      }).then(userCredential => {
        if (userCredential) {
          this.route.navigate(['/dashboard']);
        }
      });
      }

This is the Authguard service, I try to reference the login method from my authservice.service.ts, but it still redirects to users' dashboard despite I am not Logged In.这是 Authguard 服务,我尝试从我的 authservice.service.ts 引用登录方法,但尽管我没有登录,它仍然重定向到用户的仪表板。

authguard.service.ts authguard.service.ts

export class AuthguardService implements CanActivate {
  constructor(private authservice: AuthServiceService, private route: Router) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {

    let isAuthenicated = !!this.authservice.login;
    if(isAuthenicated ){
     return true;
    }
    console.log('Access denied');
    this.route.navigate(['/login']);
    return false;
  }
}

route.module.ts路由模块.ts

const routes: Routes = [
  { path: 'dashboard', component: DashboardComponent, canActivate:[AuthguardService],
     children: [
      {path: '', redirectTo: 'employees', pathMatch: 'full'},
      {path: 'employees', component: EmployeelistComponent, resolve: {employeeList: ResolverGuardService}},
      {path: 'detail/:id', component: EmployeeDetailComponent,  canActivate: [CanActivateGuardService],

      { path: 'notfound', component: PageNotFoundComponent},

     ]
    },



];

I realized that you are calling a method called login which handles a promise into AuthGuard class.我意识到您正在调用一个名为 login 的方法,该方法将承诺处理为 AuthGuard 类。

You have to handle your login method properly in order to get the correct response and save it into isAuthenicated variable.您必须正确处理您的登录方法才能获得正确的响应并将其保存到 isAuthenicated 变量中。

You maybe can do something similar to the code below.您也许可以执行类似于以下代码的操作。

AuthService.ts授权服务.ts

login(): Promise<boolean> {
  // create new promise and handle our login flow 
  return new Promise((resolve, reject) => {
    // get email and password somehow
    const = email = this.getEmail();
    const = password = this.getPassword();
    // call sign in with email and password
    return this.authz.auth.signInWithEmailAndPassword(email, password)
     .catch( error => {
       this.eventAuthError.next(error);
       // reject our promise on error
       reject(false);
      })
      .then(userCredential => {
       if (userCredential) {
         // resolve our login promise
         resolve(true);
       } else {
         // reject our promise on userCredential falsy value
         reject(false);
       }
     });
  });
}

AuthGuard.ts AuthGuard.ts

 export class AuthguardService implements CanActivate {
      constructor(private authservice: AuthServiceService, private route: Router) { }

      async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        // handling our promise properly with asnyc/await
        const isAuthenicated = await this.authservice.login();
        if(isAuthenicated ){
          // here we allow enter the page dashboard or any other
          return true;
        }
        console.log('Access denied');
        this.route.navigate(['/login']);
        return false;
      }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM