Reputation: 220
I'm trying to build an app with Ionic Capacitor. The app should use cookie for user to login. Let's say the server is example.com
and the app in Capacitor WebView is hosted under localhost
or myapp.example.com
(by changing 'server --> hostname' in capacitor.config.json
).
The problem is, when I fired a xhr-request from the app to the server, the Set-Cookie
header in the response is not accepted. Here is an example of request and response:
Request:
Host: example.com
Origin: https://myapp.example.com
Referer: https://myapp.example.com/
Content-Type: application/json
Response:
Access-Control-Allow-Methods: GET, POST, DELETE, PUT, OPTIONS, HEAD
Access-Control-Allow-Origin: *
Set-Cookie: a=something; Domain=example.com; Path=/; HttpOnly; Secure
X-Frame-Options: sameorigin
How can I get the cookie accepted in WebView? What headers should actually be set (Access-Control-Allow-*, Set-Cookie, etc.)? Is there any other special settings in the xhr-request what I am missing?
Upvotes: 6
Views: 3181
Reputation: 220
After some experiments we found the solution of the problem:
Access-Control-Allow-Credentials: true (!important)
Access-Control-Allow-Origin: (exact origin from request)
Access-COntrol-Allow-Methods: (allowed Methods)
Access-COntrol-Allow-Headers: (allowed header names)
withCredentials
of http-requests to true. In Angular we can simplely add the option withCredentials
to all requests in an interceptor.Then the Set-Cookie
header works in client WebView. Don't forget to set Domain
attribute in this header. e.g.
Set-Cookie: a=something; Domain=example.com; Path=/; HttpOnly; Secure
Upvotes: 1