【问题标题】:Angular Firebase Routeguard AuthenticationAngular Firebase Routeguard 身份验证
【发布时间】:2020-06-01 13:37:21
【问题描述】:

我实际上正在学习 Angular 和 firebase,我想在用户仪表板中添加一个路由保护,这样只有登录的用户才能查看该页面。身份验证工作正常,但我在限制没有登录用户访问用户仪表板时遇到问题这是我下面的代码。

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']);
        }
      });
      }

这是 Authguard 服务,我尝试从我的 authservice.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

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},

     ]
    },



];

【问题讨论】:

    标签: angular firebase authentication canactivate


    【解决方案1】:

    我意识到您正在调用一个名为 login 的方法,该方法处理对 AuthGuard 类的承诺。

    您必须正确处理您的登录方法才能获得正确的响应并将其保存到 isAuthenicated 变量中。

    您也许可以执行类似于下面的代码的操作。

    AuthService.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

     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;
          }
        }
    

    【讨论】:

    • 非常感谢您的回答,我真的很感激,但仍然没有工作
    • 你能用代码创建一个stackblitz项目吗?这样我就可以看到它是如何工作的,并更有效地帮助你。
    • 谢谢,我会努力做到的
    猜你喜欢
    • 2021-05-29
    • 2017-02-24
    • 2018-04-15
    • 2017-01-22
    • 2020-05-20
    • 2020-08-13
    • 1970-01-01
    • 2023-03-14
    • 2019-07-04
    相关资源
    最近更新 更多