Home > Mobile >  How to get token from oidc-client-ts (Angular)
How to get token from oidc-client-ts (Angular)

Time:01-16

auth.service.ts

import { Injectable } from '@angular/core';
import { User, UserManager } from 'oidc-client-ts';
import { SettingsService } from './settings.service';
import { Observable, from } from 'rxjs';

const url: string = 'http://localhost:44418/';

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

  userManager: UserManager;

  constructor(private appSettings: SettingsService) {
    const settings = {
      authority: appSettings.authority,
      client_id: 'client',
      redirect_uri: `${url}signin-callback`,
      silent_redirect_uri: `${url}silent-callback.html`,
      post_logout_redirect_uri: `${url}`,
      response_type: 'code',
      scope: 'openid profile offline_access scope'
    };
    this.userManager = new UserManager(settings);
  }

  public getUser(): Observable<User | null> {
    return from(this.userManager.getUser());
  }

  public login(): Observable<void> {
    return from(this.userManager.signinRedirect());
  }

  public renewToken(): Observable<User | null> {
    return from(this.userManager.signinSilent());
  }

  public logout(): Observable<void> {
    return from(this.userManager.signoutRedirect());
  }
}

login.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../code/auth.service';
import { User } from 'oidc-client-ts';
import jwt_decode from 'jwt-decode';
import { switchMap, mergeMap, tap } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  isLoggedIn: boolean = false;
  user: User;
  claims: any;

  constructor(private auth: AuthService, private http: HttpClient) { }

  ngOnInit() {
    console.log('LoginComponent.ngOnInit');
    this.auth.getUser().pipe(
      switchMap(user => {
        console.log('this never runs.'); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<< WHY?
        if (user) {
          this.isLoggedIn = true;
        }
        else {
          this.isLoggedIn = false;
        }

        if (user && user.id_token) {
          this.claims = jwt_decode(user.id_token);
          console.log(JSON.stringify(this.claims));
        }
        else {
          console.log('user is null');
        }
        return this.claims; // Seem to have to return something; don't know why.
      })
    );
  }

  login() {
    console.log('click login');
    this.auth.login()
  }

  logout() {
    console.log('click logout');
    this.auth.logout()
  }
}

Why does the code not run? How can I get the token?

CodePudding user response:

Observable didn't execute automatically.

Anatomy of an Observable

Observables are created using new Observable or a creation operator, are subscribed to with an Observer, execute to deliver next / error / complete notifications to the Observer, and their execution may be disposed.

Subscribing to Observables

A subscribe call is simply a way to start an "Observable execution" and deliver values or events to an Observer of that execution.

ngOnInit() {
  this.auth.getUser().pipe(...)
    .subscribe({
      next: (response: any) => { /* TO-DO: Handle the successful scenario */ },
      error: (err) => { /* TO-DO: Handle the successful scenario */ },
      complete: () => { /* TO-DO: Handle event after next & error */ }       
    });
}
  • Related