Необходимо обновить страницу, чтобы получить токен и профиль пользователя в Angular после аутентификации auth0. - PullRequest
0 голосов
/ 07 апреля 2019

Итак, мое SPA-приложение написано на угловом языке. Я использую auth0 для аутентификации. Когда я нажимаю «войти», я перенаправляюсь на страницу auth0, где я вхожу в систему с помощью учетной записи Google, затем я перенаправляюсь в свое угловое приложение. Проблема в том, что мне нужно обновить страницу, чтобы получить информацию о профиле пользователя или токен доступа. У меня есть пользовательская информация в navbar "никнейм и аватар", поэтому мне нужно, чтобы эта информация была получена сразу после возврата на страницу.

Я пытался разместить метод handleauthentication () во многих местах, так же, как и метод getUserProfile ().

так что это мой сервис авторизации

import { Injectable } from '@angular/core';
import * as auth0 from 'auth0-js';
import { Router } from '@angular/router';
import { environment } from 'src/environments/environment';

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

  userProfile: any;

  public  auth0 = new auth0.WebAuth({
    clientID: environment.clientID,
    domain: environment.domain,
    responseType: environment.responseType,
    audience: environment.audience,
    redirectUri: environment.redirectUri,
    scope: environment.requestedScopes
  });


  constructor(private router: Router) {
  }

  public getProfile(cb): void {
    const accessToken = localStorage.getItem('access_token');
    if (!accessToken) {
      throw new Error('Access Token must exist to fetch profile');
    }
    const self = this;
    this.auth0.client.userInfo(accessToken, (err, profile) => {
      if (profile) {
        self.userProfile = profile;
        console.log(self.userProfile);
      }
      cb(err, profile);
    });
  }

  public login() {
    this.auth0.authorize();
  }

  public handleAuthentication(): void {
    this.auth0.parseHash((err, authResult) => {
      if (authResult && authResult.accessToken && authResult.idToken) {
        window.location.hash = '';
        this.setSession(authResult);
        this.router.navigate(['/home']);
      } else if (err) {
        this.router.navigate(['/error']);
        console.log(err);
        alert('Error: ${err.error}. Check the console for further details.');
      }
    });
  }

  private setSession(authResult): void {
    const expiresAt = JSON.stringify(authResult.expiresIn * 1000 + new Date().getTime());
    const scopes = authResult.scope || environment.requestedScopes || '';

    localStorage.setItem('access_token', authResult.accessToken);
    localStorage.setItem('id_token', authResult.idToken);
    localStorage.setItem('expires_at', expiresAt);
    localStorage.setItem('scopes', JSON.stringify(scopes));
    console.log(localStorage.getItem('access_token'));
  }




  public logout(): void {
    localStorage.removeItem('access_token');
    localStorage.removeItem('id_token');
    localStorage.removeItem('expires_at');
    localStorage.removeItem('scopes');
    this.router.navigate(['/']);
  }

  public isAuthenticated(): boolean {
    const expiresAt = JSON.parse(localStorage.getItem('expires_at'));
    return new Date().getTime() < expiresAt;
  }

  public userHasScopes(scopes: Array<string>): boolean {
    const grantedScopes = JSON.parse(localStorage.getItem('scopes')).split(',');
    return scopes.every(scope => grantedScopes.includes(scope));
  }

  public renewToken() {
    this.auth0.checkSession((err,result) => {
      if(!err){
        this.setSession(result);
      }
    })
  }
}

Мой компонент приложения

import { PostService } from './services/post.service';
import { ProfileService } from './services/profile.service';
import { Component, OnInit } from '@angular/core';
import { AuthService } from './services/auth.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'SchoolGit';

  constructor(public auth: AuthService, private postService: PostService) {
    auth.handleAuthentication();
  }

  ngOnInit() {
    this.postService.getMessage();
  }
}

и мой navbar ts

import { ProfileService } from './../../services/profile.service';
import { AuthService } from './../../services/auth.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {
  profile: any;

  constructor(private auth: AuthService) { }

  ngOnInit() {
    if (this.auth.userProfile) {
      this.profile = this.auth.userProfile;
    } else {
      this.auth.getProfile((err, profile) => {
        this.profile = profile;
      });
    }
  }

  login(): void {
    this.auth.login();

  }

  logout(): void {
    this.auth.logout();
  }

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

мой компонент обратного вызова пуст

Мне нужно получить профиль пользователя после перенаправления в угловое приложение, а не после нажатия кнопки «Обновить».

...