HttpClient Headers authentication not working

I am on Ionic 3 and Angular 6. When I tried the following code on the browser, it works. But when I test it on my iPhone for the iOS, it keeps showing 401 Error, authentication credentials were not provided.

Here’s the request response.

{"url":"https://example.com/api/v1/users/id1234","body":null,"reportProgress":false,"withCredentials":false,"responseType":"json","method":"GET","headers":{"normalizedNames":{},"lazyUpdate":[{"name":"Authorization","value":"Token","op":"s"}],"headers":{},"lazyInit":{"normalizedNames":{},"lazyUpdate":null,"headers":{}}},"params":{"updates":null,"cloneFrom":null,"encoder":{},"map":{}},"urlWithParams":"https://example.com/api/v1/users/id1234"}**

here’s my home.ts

facebookLogin() {
    let auth = this.authProvider;
    let account = auth.userAccount;

    this.fb.login(['public_profile'])
      .then((res: FacebookLoginResponse) => {
        if (res.status == "connected") {
          auth.isLoggedIn = true;
          auth.loginOption = 0;
          this.getFacebookDetail();
        }
      })
      .catch(err => {
        console.log('Error logging into Facebook: ', err);
      });
  }

  getFacebookDetail() {
    let auth = this.authProvider;
    let account = auth.userAccount;
    let profile = auth.userProfile;
    this.fb.api('/me?fields=id,first_name,last_name,picture,email', [])
      .then(res => {
        console.log('Facebook return information: ')
        console.log(res);
        account.account_id = res.id;
        account.username = null;
        account.email = res.email;
        profile.first_name = res.first_name;
        profile.last_name = res.last_name;
        profile.picture_url = res.picture.data.url;
        this.nativeStorage.setItem('user', account);
      })
      .then(() => {
        this.getUserAccount(account.account_id);
      })
      .catch(err => {
        console.log('Error when getting facebook detail: ', err);
      });
  }
  
  getUserAccount(id) {
    let auth = this.authProvider;
    return new Promise(resolve => {
      this.http.get<IUserAccount>(this.baseUrl + '/users/' + id)
        .subscribe(res => {
          console.log(res);
          auth.getUserProfile(id);
          this.navCtrl.setRoot('TabsPage', {
            picture_url: auth.userProfile.picture_url,
            isLoggedIn: auth.isLoggedIn
          });
        }, (err: HttpErrorResponse) => {
          if(err.error instanceof Error) {
            console.log('Client-side error occrued');
          } else {
            console.log('Server-side error occrued');
          }
          this.navCtrl.push('SetupPage');
        });
    });
  }

here’s interceptor.ts

import { _throw } from 'rxjs/observable/throw';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';


@Injectable()
export class AuthHttpInterceptor implements HttpInterceptor{

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const authReq = req.clone({
      setHeaders: {'Authorization': 'Token XXXXXXXXX'},
    });

    return next.handle(authReq).do(
      succ => {
        console.log(succ);
      },
      err => {
        if(err.status === 401) {
          console.error('You are not authenticated!')
        }
      }
    );
  }
}

If I get you code right you send the string ‘Token’ as authorization in the header.
I think you have to replace the string ‘Token’ with the real token.

I did use real token in there, I just removed it here because I do not want to share that information. The key is the code works fine when it is on browser, but when I try it on app, it does not work. But I will change it up a bit so it’s clear.

:smile: Ok my fault I’m sorry…

Ok I took a look in an interceptor I use and I found one difference:

I use

setHeaders: req.headers.set('Authorization', xxxxxxx)

Thanks for replying!

Do you mean headers: req.headers.set('Authorization', xxxxxxx)? this should be the same as
setHeaders: {'Authorization': 'xxxxxxx'}, I tried both, the result is the same.

I mean change

const authReq = req.clone({
      setHeaders: {'Authorization': 'Token XXXXXXXXX'},
    });

to

const authReq = req.clone({
      headers: req.headers.set('Authorization', 'Token xxxxxxx')
    });

If the result is the same perhaps on your device the token is not read properly or something else happens.

The interceptor looks good.

Yea I tried, it’s the same. I have turned off the authentication on the server end to for testing purpose and everything else works fine. I read on other places it seems like it might be a server-end issue. I will double check and post the solution here if I can figure it out.

I confess to having a bit of curiosity about how the token finds its way to the interceptor. Is it really a hardcoded constant string as has been implied here so far?

I figured it out… it was a stupid ‘/’ missing at the end of the API that makes it not working on the device, but it is still working on browser…

I’ve logged in just to say thank you, you saved me.
I owe you a cup of coffee.