简体   繁体   中英

auth0 with angular2 - how to get token

I'm using auth0 and downloaded the quickstart sample app from here . I'm trying to get the id_token so I can get the user's profile. However, I'm not able to, as the auth.service is running after my other pages load.

So, I have a home.component like this:

import { Component, OnInit } from '@angular/core';
import {Auth} from './auth.service';

@Component({
  selector: 'home',
  template: `
    <h1>Testing</h1>
    `,
  providers: [Auth],
})

export class HomeComponent implements OnInit {

 constructor(private auth: Auth) {}

 ngOnInit(){
     var token = localStorage.getItem('id_token');
     var profile = this.auth.lock.getProfile(token, function(error, profile) {
     if (error) {
       console.log("there was an ERROR" + error + token);
       return;
     }});    
   }
}

and my auth.service class that looks like this:

declare var Auth0Lock: any;

@Injectable()
export class Auth {
// Configure Auth0
lock = new Auth0Lock(mycreds, mycreds, {});

 constructor() {
    // Add callback for lock `authenticated` event
    this.lock.on("authenticated", (authResult) => {
    console.log("IN AUTH.SERVICE");      
    localStorage.setItem('id_token', authResult.idToken);                   
  });          
}

public login() {
  // Call the show method to display the widget.
  this.lock.show();        
};

public authenticated() {
// Check if there's an unexpired JWT
// This searches for an item in localStorage with key == 'id_token'

return tokenNotExpired();
};

  public logout() {
    // Remove token from localStorage
    localStorage.removeItem('id_token');
  };
}

the issue is that my home.component class loads before my auth.service, so when I try to get the user token, it's not there yet. I'm pretty new to angular so I'm not sure how to make one page load before another or how to solve this problem.

The service is instantiated and the constructor run way before your HomeComponents OnInit event is raised. The thing is, your service is waiting for a response (auth) before it sets the token.

That said - you can't expect there to be a token in your init on the HomeComponent. You're not getting the token untill the user actively logged in through the Auth0Lock component. All you can do in your HomeComponent is call auth.login(). Since your user on the callback might have been authenticated, the token might be there - you could check in your HomeComponent if the token is there (auth.authenticated()) before you request the profile data.

A couple questions for you: 1. Did you check your console if you're getting errors? 2. Are you ever getting the "IN AUTH.SERVICE" message from your auth callback?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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