How to configure apollo-angular to use access token?

I am able to login with the provided tutorial (login/logout button) However, trying to get an access token to configure it so that apollo will send the Authorization header is not working. I get a token but it is a very short token and not a JWT access token.

dependencies in package.json:
"dependencies": { "@angular/animations": "~11.0.0", "@angular/common": "~11.0.0", "@angular/compiler": "~11.0.0", "@angular/core": "~11.0.0", "@angular/forms": "~11.0.0", "@angular/platform-browser": "~11.0.0", "@angular/platform-browser-dynamic": "~11.0.0", "@angular/router": "~11.0.0", "@apollo/client": "^3.0.0", "@auth0/auth0-angular": "^1.2.0", "apollo-angular": "^2.1.0", "graphql": "^15.0.0", "rxjs": "~6.6.0", "tslib": "^2.0.0", "zone.js": "~0.10.2" },

graphql.module.ts:
`
import {NgModule} from ‘@angular/core’;
import {APOLLO_OPTIONS} from ‘apollo-angular’;
import {ApolloClientOptions, InMemoryCache} from ‘@apollo/client/core’;
import {HttpLink} from ‘apollo-angular/http’;
import { setContext } from ‘@apollo/client/link/context’;
import { from } from ‘@apollo/client/core’;
import { AuthService } from ‘@auth0/auth0-angular’;
import { ConfigService } from ‘./config.service’;

export function createApollo(httpLink: HttpLink, configService: ConfigService, authService: AuthService): ApolloClientOptions {
const auth = setContext(async (_, { headers }) => {
const token = await authService.getAccessTokenSilently().toPromise();

console.log({token});

return {
  headers: {
    ...headers,
    Authorization: `Bearer ${token}`,
  },
};

});

return {
link: from([
auth,
httpLink.create({ uri: configService.apiUri }),
]),
cache: new InMemoryCache(),
};
}

@NgModule({
providers: [
{
provide: APOLLO_OPTIONS,
useFactory: createApollo,
deps: [HttpLink, ConfigService, AuthService],
},
],
})
export class GraphQLModule {}
`

Hey @barrett, Welcome to the Auth0 community!

To call an API you can have a look at this tutorial:

The main crux is to use Audience in AuthModule.forRoot.

Let me know if this helps!

Regards,
Sid

1 Like

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.