Angular 6中的异步authguard [英] Async authguard in angular 6

查看:176
本文介绍了Angular 6中的异步authguard的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在允许访问Angle中的特定路由之前提供服务器端身份验证.

I would like to provide a server-side authentication before I give access to a specific route in angular.

我有一个实现CanActivate的AuthGuard和一个服务AuthService. authService已经有一个private loggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(null); ,视图会订阅该private loggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(null); 以便知道用户是否已登录.我真的不知道我的方法是否错误,但这似乎行不通.

I have a AuthGuard which implements CanActivate and a service AuthService. The authService already has a private loggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(null); which views subscribe to in order to know if the user is logged in or not. I don't really know if my approach is wrong, but it does not seem to work.

这是我在auth.guard.ts中拥有的东西:

This is what I have in auth.guard.ts:

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

这是auth.service.ts:

and this is auth.service.ts:

    @Injectable()
export class AuthService {
    private loggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(null);

    constructor(
        private router: Router,
        private http: HttpClient
    ) {

    }

    get isLoggedIn() {
        return this.loggedIn.asObservable();
    }

    isAuthenticated() : Observable<boolean> {
        const headers = new HttpHeaders().set("X-Requested-With", "XMLHttpRequest");

        return this.http.get('/user', {headers: headers}).map(
            response => {
                if (response['username']) {
                    this.loggedIn.next(true);
                    return true;
                } else {
                    return false;
                }
            }
        )
    }

推荐答案

这是RXJS6的方法,在身份验证服务中添加了变量_isAuthenticated,以仅在禁用标志时请求服务器状态.希望对别人有帮助.

Here is approach for RXJS6, added a variable _isAuthenticated in authentication service to request the server state just when the flag is disabled. I hope that helps others.

确保canActivate返回纯布尔值或可观察值.路由处理程序将订阅给定的observable,并对来自值流的第一个布尔值做出反应.

Ensure canActivate returns a plain boolean or an observable. The route handler will subscribe to the given observable and reacts to first boolean value coming from the value stream.

auth.guard.ts

auth.guard.ts

import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';

import { Observable } from 'rxjs/';
import { map, finalize } from 'rxjs/operators';
import { DataService } from '../data.service';
import { AuthenticationService } from './authentication.service';

@Injectable()
export class AuthenticationGuard implements CanActivate {

  constructor(private router: Router,
              private dataService: DataService,
              private authenticationService: AuthenticationService) { }

  canActivate(): any {
    const isAuthenticated = this.authenticationService.isAuthenticated();

    // All good
    if ( isAuthenticated ) {
      return true;

    // Hmm, let's verify the user first
    } else {
      return this.authenticationService.isSessionAlive()
        .pipe(
          map(res => {

            // No valid session; let's move to the login page
            if ( res === false ) {
              this.router.navigate(['/login'], { replaceUrl: true });
            }

            return res;
          })
        );
    }
  }

}

auth.service.ts(我正在使用rxjs 6)

auth.service.ts (I'm using rxjs 6)

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { DataService } from '@app/core';

@Injectable()
export class AuthenticationService {

  private _isAuthenticated = false;

  constructor(
    private dataService: DataService
  ) {}

  isAuthenticated(): boolean {
    return this._isAuthenticated;
  }

  isSessionAlive(): Observable<any> {
    return Observable.create((observer) => {
      this.dataService.SessionIsAlive()
        .subscribe((res) => {
          this._isAuthenticated = true;
          observer.next(res.success); // your server response
        }, (err) => {
          this._isAuthenticated = false;
          observer.next(false);
          // observer.error(err); // won't work here you need to use next
        });
    });
  }
}

这篇关于Angular 6中的异步authguard的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆