le0
le0

Reputation: 851

How can a firebase auth token be send to a external server?

I am trying the following code:

firebase
    .auth()
    .signInWithEmailAndPassword(this.email, this.password)
    .then(function(user) {

      let token = user.getIdToken(true);
      if (token) {
        axios.post('http://localhost:3000/verify_token', {
          idtoken: token
        })

But I am getting the error in browser:

TypeError: Converting circular structure to JSON
at JSON.stringify (<anonymous>)
at transformRequest (defaults.js?2822:51)
at transform (transformData.js?4cd5:16)
at Object.forEach (utils.js?7061:224)
at transformData (transformData.js?4cd5:15)
at dispatchRequest (dispatchRequest.js?c4bb:37)
at <anonymous>

How can I send the token to a external server ? The properties of token's JSON aren't clear. They're letters from "a" to "i".

Upvotes: 1

Views: 992

Answers (3)

M&#39;Boulas
M&#39;Boulas

Reputation: 131

I hope this will help everyone else.

In your auth.service.ts file:

import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import { HttpClient } from '@angular/common/http';
import * as firebase from 'firebase/app';

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

  constructor(private afAuth: AngularFireAuth, private http: HttpClient) {}

  getIdToken() {
   // Call getIdToken() from your login component
   // And then listen to the auth status change
   this.afAuth.auth.onAuthStateChanged(userAuth => {
     if (userAuth) {
       // When user is signed in, you can get their user id as a test
       console.log('User ID: ' + userAuth.uid);

       // Get Id Token of the currently signed in user
       firebase.auth().currentUser.getIdToken()
         .then(function(idToken) {
           console.log('idToken is: ', idToken);
           // Return this idToken and get it in the next promise
           return idToken;
         })
         .then((token) => {
            const idTokenJSON = {
              id_token: token
            };
           // Always set the response type in your http request.
           // Here the type is {message: string, data: {id_token: string}}
           this.http.post<
                          {message: string, data: {id_token: string}}
                         >('http://server_domain.com/check_id_token', idTokenJSON)
             .subscribe((response) => {
               console.log('response data: ', response.data);
               console.log('response message: ', response.message);
             });
         })
         .catch(function(error) {
           // Handle error
         });
     } else {
       console.log('No user is signed in.');
     }
   });
  }
}

After grabbing the id token, you must chain another promise in which you send the token to the server. Here, I'm using the Angular HttPClient. But a regular HTTPS POST request should do as well, as it follows:

var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://server_domain.com/check_id_token');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
  console.log('Signed in as: ' + xhr.responseText);
};
xhr.send('idtoken=' + token);

Please let me know if this helps.

Upvotes: 0

Ali Faris
Ali Faris

Reputation: 18592

user.getToken() return promise not token value you need to call then on the promise or use await

using then

let token = user.getIdToken(true).then(token => 
{
    if (token) {
        axios.post('http://localhost:3000/verify_token', {
        idtoken: token
    });
}).catch(e => {/*DO SOMETHING*/});

using await

try{
    let token = await user.getIdToken(true);
    if (token) {
        axios.post('http://localhost:3000/verify_token', {
        idtoken: token
    });
}catch(e){/*DO SOMETHING*/}

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317322

According to the documentation for getIdToken(), it returns a promise containing a string, which is the token you're looking for.

Right now, your code is assuming that the string is returned directly. instead, you'll have to call then() on that promise to get the actual token for your request.

Upvotes: 1

Related Questions