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!')
}
}
);
}
}