API Project CORS - for Mobile App - help!

I’m trying to set up a new Mobile App to connect to an existing web project and am going round in circles a little.

It appears that CORS needs to be enabled for external devices to be able to use the endpoints. I have enabled it in the web project but if you use * you can’t use the ‘credentials’ attribute so it fails to set the log in cookie. But then each device type seems to use a different value for the origin:
Web: http:localhost:PORTNUMBER (primarily used to test)
IOS: capacitor://localhost
Android: http:localhost

How should it be set up on the WEB API project to allow login/security provider but still cope with each device?

Here’s what works for me on iOS and Android.

Yes, use credentials on all server connects.

In config.xml under the platform android section add the following ( I’m pretty sure this defaults to false and thus could be removed entirely, but I know having it works. :slight_smile: ):

<preference name="AndroidInsecureFileModeEnabled" value="false" />  

For both ios and android sections, include a hostname preference:

<preference name="hostname" value="domain.com" />

For ios only add scheme:

<preference name="scheme" value="app" />

I think that is all that is relevant in config.xml.

Now on the server project you need to enter the following in the CORS property:

app://domain.com

If you are like me, I have multiple domains pointing to this, so I manually edit the config.json with an array of domains:

  "cors": {
    "origin": [
      "app://domain.com",
      "app://domain2.com",
      "app://domain3.com"
    ]
  },

I’m using Cordova platforms ios 6.2.0 and Android 11.0.0 and targeting android sdk 32

3 Likes

Thanks Ken,
I’ll give that a go. Appreciate the quick response - it has been driving me mad!

1 Like

I was trying with Capacitor and there seems to be some work to do as there’s version mismatches/dependencies etc. that don’t work out-of-the-box. Cordova though is a breeze in comparison…

Your code worked a treat. Thank you so much! :beers:

@george Could this be added to the UI to make starting a mobile app project easier?

4 Likes

Did you ever find out how to get this to work with Capacitor?

I can get it to work with Cordova using the code above but not Capacitor. With the recent updates (local database and camera) I want to use Capacitor.

I have tried changing the capacitor.config.json file to try and mimic the code above but I can’t get it right.

1 Like

I just used Cordova in the end. Was planning another crack at capacitor soon with the new features but haven’t had time yet

1 Like

Thanks for getting back to me.

I can see this was assigned to George. @George Did you ever have chance to look into this or know a work around?

1 Like