skip to Main Content

I’ve been running into some hiccups with Ionic while making requests to my database. I want to talk about the login endpoint, where we authenticate users using Firebase. After that, we use the response data to make a second request to the database, where we grab an AccessToken and a RefreshToken for further interactions.

But heer comes the issue, everything works perfectly fine in the browser. I’ve tested it across different browsers and no issues there. But as soon as I try to run the app on an emulator or directly on my phone, this problem starts popping up.

enter image description here

And just for reference that the endpoint does indeed work, here is a snippet from Postman. (Hard to actually show anyone that the endpoint is working from the app, as the app redirects directly after a successful Login)

enter image description here

Code

AuthService

login(email:string, password:string){
    return this.httpClient.post<AuthResponseData>(`https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=${environment.firebaseAuthApiKey}`,
    {
      email:email, 
      password:password,
      returnSecureToken:true
    }).pipe(tap(this.setUserData.bind(this)), switchMap(firebaseResponse =>{
      return this.databaseService.loginUser(firebaseResponse.localId, firebaseResponse.email);
    }), tap((response:LoginResponseData) => {
      this.databaseService.setCredentials(response);
    }));
  }

DatabaseService
loginUser(userId:string, email:string){
    const headers = new HttpHeaders({
      'Content-Type': 'application/json',
    });
    return this.httpClient.post<LoginResponseData>(this.url + "login",{"userId": userId, "email": email}, { headers });
  }

Now since the error I am getting is apparently getting though the Firebase Request but then having issues with the request to my database here is also the beginning of my index.php for the API

if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');    // cache for 1 day
}

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: DELETE, PATCH, GET, POST, OPTIONS");
    
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

    exit(0);
}

And ofcourse the AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true">
        
        <activity
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode"
            android:name=".MainActivity"
            android:label="@string/title_activity_main"
            android:theme="@style/AppTheme.NoActionBarLaunch"
            android:launchMode="singleTask"
            android:exported="true">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

        </activity>

        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"></meta-data>
        </provider>
    </application>

    <!-- Permissions -->
    
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

    <!-- GeoLocation -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-feature android:name="android.hardware.location.gps" />

    <!-- Camera -->
    <uses-permission android:name="android.permission.READ_MEDIA_IMAGES"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>

2

Answers


  1. Chosen as BEST ANSWER

    I figured out what was causing my problem. It was pretty specific to my situation. I was getting an error because my SSL certificate didn't match my domain. So, I went ahead and deleted all my SSL certificates and got new ones. That fixed the issue, and now my app is running without any problems. I'm keeping this post up because @Íñigo Enrique Hernández's does provide some valuable information.


  2. in a device try to use ‘@awesome-cordova-plugins/http/ngx’

    i do it like this:

    if(this.platform.is("cordova")){
     return this._http.post("**************/CambiarPass",_datos, {}).then((result:any)=>{
          resolve(result.data);
      }).catch((error:any) =>{
          resolve(error);
      });
    }else{
       return this.http.post("/api/CambiarPass",{email:email, codigo:codigo, nueva:nueva},httpOptions).toPromise().then((result:any)=>{
           resolve(result);
       }).catch((error:any) =>{
           console.log(error);
           resolve(error);
        });
    }
    

    my imports:

    import { HttpClient, HttpHeaders } from '@angular/common/http';
    import { HTTP } from '@awesome-cordova-plugins/http/ngx';
    

    my contrusctor:

      constructor(
        private _http: HTTP,
        private http: HttpClient,
      ) {}
    

    options

      public httpOptions:any = {
        headers: new HttpHeaders({
            'Access-Control-Allow-Origin': '*',
            'Content-Type': 'application/json; charset=utf-8'
        })
      };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search