Auth0 Home Blog Docs

Get jwt token with angular sdk

hi i am using angular 8 and “auth0-spa-js” for auth0 integration…

how to get jwt token in successful login of user (like successful login of gmail)?

Hey there!

Not an Angular guy myself but I think this SDK can get you there:

my plat form is angular 8 not angular js.it complete diff from angular js.

i tried like below.i am getting access token but for my back-end i need jwt.

 async getAuth0Client(): Promise<Auth0Client> {
    if (!this.auth0Client) {
      this.auth0Client = await createAuth0Client({
        domain: config.domain,
        client_id: config.clientId,
        
        redirect_uri: `${window.location.origin}/callback`
      });

  try {
   
    this.isAuthenticated.next(await this.auth0Client.isAuthenticated());

    this.isAuthenticated.subscribe(async isAuthenticated => {
      if (isAuthenticated) {
        const client = await this.getAuth0Client();
        const token = await client.getTokenSilently()
        console.log(token)=>>> here i am getting access token..
        return this.profile.next(await this.auth0Client.getUser());
      }

      this.profile.next(null);
    });
  } catch { }

  return this.auth0Client;
}

return this.auth0Client;

}

and i am getting user profile also.

Hi @xprsloop,

as mentioned in

you need to pass the audience parameter in the getTokenSilently request, such as:

const token = await client.getTokenSilently({audience: 'https://example-api/});

then you get the access token in JWT format, which you can then use to make calls against your backend.

(It’s the same approach with the auth0-spa-js in Angular2 as it is with Angular8.)

when i am doing i am getting below error>
"Object: {"error":"login_required","error_description":"Login required","state":"LkR+cnZDMHQtWHNtWUxsNTh5akU4QXd2Z0ZJaW5yflJmNUFBb0hWRGUtdw=="}"

and my Ts code is :

 const client = await this.getAuth0Client();
 const token = await client.getTokenSilently({scope:'profile',audience:'my Identifier'})

when i pass "profile","openid" in scope param ,i am getting same error

could help me or is any code snippet for getting jwt token for angular 8

if you want i will share my “Identifier”

  1. do i need to register my front-end- app with aobe “Identifier” in api < dashboard in my dashboard section?

Sorry, the getTokenSilently alone was used in the other thread in another context. In this case, it’s the loginWithRedirect or loginWithPopup that needs to be called first.

It’s basically this quickstart example:

but add scope' andaudience` to it the AuthClient constructor.

For the initial login, use loginWithRedirect or loginWithPopup (when the user clicks the login button):

  async ngOnInit() {
    this.auth0Client = await this.authService.getAuth0Client();
    [...]
  }

  [...]

  async login() {
    await this.auth0Client.loginWithRedirect({
      scope: 'openid profile email read:messages',  // put scope and audience either in here at the login
      audience: 'https://example-api/',             // or in the constructor as shown below. 
      redirect_uri: `${window.location.origin}/callback`
    });
  }

while this is the service class with the constructor and sample where the access token is being fetched:

  async getAuth0Client(): Promise<Auth0Client> {
    if (!this.auth0Client) {
      this.auth0Client = await createAuth0Client({
        domain: config.domain,
        client_id: config.clientId,
        scope: 'openid profile email read:messages',  // put scope and audience either in here 
        audience: 'https://example-api/',             // or when making the login request. 
        redirect_uri: `${window.location.origin}/callback`
      });

      try {
        this.isAuthenticated.next(await this.auth0Client.isAuthenticated());

        // get the access token here in JWT format
        const accessToken = await this.auth0Client.getTokenSilently();
        console.log( JSON.stringify(accessToken) );

        this.isAuthenticated.subscribe(async isAuthenticated => {
          if (isAuthenticated) {
            return this.profile.next(await this.auth0Client.getUser());
          }

          this.profile.next(null);
        });
      } catch {}

      return this.auth0Client;
    }

    return this.auth0Client;
  }

ok. i will try with above code…

  1. when i am reloading my application again isAuthenticated returning false.how to fix

shell i store in localstorage when user first time login.

No, don’t store any tokens in localStorage.

The SDK handles it automatically via Silent Authentication (getTokenSilently). However, if you’re using social connections like Google and the New Universal Login (ULP), it only works if you’re using proper Google API Keys and not the development keys provided by Auth0.

See related thread regarding this:

so,if i use production key ,auth0 will handle autometically ,is it?

Either way the SDK will try to get the token silently, however, with dev keys it will fail. Therefore it will only work with production keys.

ok.Thanks you very much