Angular 6 - JWT - проверка аутентификации / авторизации пользователя при прямом обращении пользователя к URL - PullRequest
0 голосов
/ 06 июля 2018

Я реализовал аутентификацию JWT в своем приложении Angular 6 после перехода с 4 на 6. Пользователь входит в приложение Angular, и всякий раз, когда он пытается получить доступ к странице, используя URL-адрес в адресной строке, приложение повторно инициализируется и вынуждает снова войти в систему. Ниже мой Authguard & SecurityService. Я хочу проверить, авторизован ли уже пользователь, и нет необходимости снова проходить аутентификацию и проверять сохраненный токен.

export class AuthGuard implements CanActivate {
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    //return true;
    // Get property name on security object to check
    let authProp: string = next.data["securityPropertyName"];
    let isRouteAccessible = this.securityService.securityObject.AccessibleMenus
                                .map(function(e) { return e.menuName; }).indexOf(authProp);
    if (this.securityService.securityObject.isAuthenticated
      && isRouteAccessible > -1) 
      {    
        return true;
    }    
    else {
      this.router.navigate(['login'],
        { queryParams: { returnUrl: state.url } });
      return false;
    }
  }
  constructor(private securityService: SecurityService, private router: Router) { }
}


@Injectable({
  providedIn: 'root'
})
export class SecurityService {
  securityObject: AppUserAuth = new AppUserAuth();
  constructor(private http: HttpClient) { }

  resetSecurityObject(): void {
    this.securityObject.userName = "";
    this.securityObject.bearerToken = "";
    this.securityObject.isAuthenticated = false;
  
    this.securityObject.AccessibleMenus = [];        
  
    localStorage.removeItem("bearerToken");
  }
  login(entity: AppUser): Observable<AppUserAuth> {
    // Initialize security object
  this.resetSecurityObject();

  return this.http.post<AppUserAuth>(API_URL + "login",
      entity, httpOptions).pipe(
      tap(resp => {
        // Use object assign to update the current object
        // NOTE: Don't create a new AppUserAuth object
        //       because that destroys all references to object
        Object.assign(this.securityObject, resp);

        
        // Store into local storage
        localStorage.setItem("bearerToken", 
            this.securityObject.bearerToken);
      },
      (err)=>{
        console.log(err);
      }
    ));
  }
  logout(): void {
    this.resetSecurityObject();
  }
}
...