Angular - Access Token

I really have no idea how to get the access token or id token from the session. Any help would be appreciated.
I’ve followed these articles with no success.

https://developer.okta.com/docs/api/resources/oidc#token
https://developer.okta.com/blog/2017/04/17/angular-authentication-with-oidc

This tutorial has an example: https://developer.okta.com/blog/2017/06/13/add-authentication-angular-pwa

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { OAuthService } from 'angular-oauth2-oidc';

@Injectable()
export class BeerService {

  constructor(private http: HttpClient, private oauthService: OAuthService) {}

  getAll(): Observable<any> {
    return this.http.get('http://localhost:8080/good-beers', {headers: this.getHeaders()});
  }

  getHeaders(): HttpHeaders {
    return new HttpHeaders().set('Authorization', this.oauthService.authorizationHeader());
  }
}

In case you’re using Okta’s Angular SDK, here’s another tutorial that uses an HttpInterceptor:

https://developer.okta.com/blog/2017/12/04/basic-crud-angular-and-spring-boot

import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromPromise';
import { OktaAuthService } from '@okta/okta-angular';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  constructor(private oktaAuth: OktaAuthService) {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return Observable.fromPromise(this.handleAccess(request, next));
  }

  private async handleAccess(request: HttpRequest<any>, next: HttpHandler): Promise<HttpEvent<any>> {
    // Only add to known domains since we don't want to send our tokens to just anyone.
    // Also, Giphy's API fails when the request includes a token.
    if (request.urlWithParams.indexOf('localhost') > -1) {
      const accessToken = await this.oktaAuth.getAccessToken();
      request = request.clone({
        setHeaders: {
          Authorization: 'Bearer ' + accessToken
        }
      });
    }
    return next.handle(request).toPromise();
  }
}

NOTE: This tutorial uses Angular 5. I plan to write another for Angular 6 soon.

Hey Matt, I tried following along and added this to my app.component.ts file

getAll(): Observable<any> {
    return this.http.get('http://localhost:4200/', {headers: this.getHeaders()});
  }

  getHeaders(): HttpHeaders {
    return new HttpHeaders().set('Authorization', this.oauthService.authorizationHeader());
  }

ngOnInit() {
    this.oktaSignIn.session.get((response) => {
      if (response.status !== 'INACTIVE') {
        this.user = response.login;
        this.changeDetectorRef.detectChanges();
      } else {
        this.showLogin();
      }
    });
    this.getAll();
    this.getAll().subscribe((data) => console.log(data));
  }

I’m still not seeing the access token. What am I doing wrong?

Why do you want the access token? What are you trying to do with it? You only really need it if you want to call a backend API that’s protected by Okta.

The client I’m working with is using Okta to set user GroupsClaims. So if a user is in Group X, they can only see certain components/etc and if a user is in Group Y, they can only see certain components/etc.

In that case, you probably want to get the ID token. But then you’d have to parse it. There is a getUser() method that’s available in the Angular SDK that you can get claims from. For example:

  async ngOnInit() {
    this.isAuthenticated = await this.oktaAuth.isAuthenticated();
    if (this.isAuthenticated) {
      const userClaims = await this.oktaAuth.getUser();
      this.userName = userClaims.name;
    }
  }

Example from https://github.com/okta/samples-js-angular.

FWIW, there’s an open issue to add a directive that allows you to show/hide elements. https://github.com/okta/okta-oidc-js/issues/36

Even with this.oktaAuth.$authenticationState.subscribe(isAuthenticated => this.isAuthenticated = isAuthenticated); in my constructor I’m getting this.isAuthenticated is false?

Can you try making the sample app work with your org and see if that works?

I used the sample and changed the default-config.ts file and used my org credentials and I can login successfully.

So now you should have an example that allows you to view the claims in the ID token. Is that enough for you to solve the problem in your application?

I’ll have to configure some things since the application is set up differently. But thanks Matt! I really do appreciate all your help!

@mraible You mentioned above that you were planning on creating an Angular 6 version to get the AccessToken (at least that is the way I read it.) Did you every create it? If so, do you have a link. (I did a quick search and I could not find it.)

I am currently working on an Angular 7 app with a .Net Core API. I am having a problems with it. I think my issue is getting the AccessToken.

Let me know. Thanks.

Yep! See https://developer.okta.com/blog/2018/08/22/basic-crud-angular-7-and-spring-boot-2

You can also use OktaDev Schematics to quickly add Okta Auth to a new Angular CLI app.

Hope this helps!

Hi,

It seems that all examples are using @angular/common/http is there an example on how to use Okta SDK with older @angular/http?

The issue I am having is that I don’t want to change my methods to async/await and hence can’t execute await this.oktaAuth.getAccessToken();

I understand it is possible to extend http and implement “Interceptor” functionality but is there an example of how to do that with Okta SDK?

thanks