Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[docs]How the project supports CORS #26

Closed
Grewer opened this issue Apr 26, 2020 · 26 comments
Closed

[docs]How the project supports CORS #26

Grewer opened this issue Apr 26, 2020 · 26 comments

Comments

@Grewer
Copy link

Grewer commented Apr 26, 2020

As the title
And https://github.com/tauri-apps/tauri/blob/7e2854007a/cli/tauri.js/src/template/defaultConfig.ts whether his config description can be added to Wiki

@Grewer
Copy link
Author

Grewer commented Apr 27, 2020

In electron it looks like this:

  webPreferences: {
         webSecurity: false,
  },

@nothingismagick
Copy link
Member

We're about to push a few updates to master and cut a new release. As soon as that lands, I will update the wiki to go into gory details about the config.

To answer your question in the meantime, we apply a CSP - but haven't added CORS for the mode that uses a server. We are using tiny-http for the server we ship with the app, but perhaps we should also offer an option for adding a configurable Access-Control-Allow-Header. Thanks for the reminder @Grewer

@nothingismagick nothingismagick transferred this issue from tauri-apps/tauri Apr 29, 2020
@Laegel
Copy link
Member

Laegel commented Jun 2, 2020

As discussed internally, it's planned to add the following items to the docs:

@Zulko
Copy link

Zulko commented May 10, 2021

Hello! Thanks for the great project. I believe I have the same question as the original poster. In particular, is it possible to de-activate CORS checks in Tauri?

@nothingismagick
Copy link
Member

Wow, this is an old issue.

Anyway, to turn off the CSP in the webview, do this:

  "tauri": {
    "security": {
      "csp": ""
    }
  }

However, this really only limits what the webview can do. If you want to sidestep CORS restrictions, then you need to perform your request outside of the browser context. This article is a great read: https://blog.container-solutions.com/a-guide-to-solving-those-mystifying-cors-issues

A final word of warning: you may actually be breaking the terms and conditions of the service you are attempting to retrieve data from / send data to. Doing so as a developer may actually open you up to a class action lawsuit if your users/customers find out about this or they themselves get in trouble. An example might be such as building your own Discord app. I believe that they frown upon this and are known to mercilessly delete accounts involved in such a thing.

So, if you wanted to sidestep CORS limitations placed on the browser, what you could try is to craft a request using our HTTP API and have the Rust side make the request, returning the results (after potentially filtering them???) to the webview.

Please see:
https://tauri.studio/en/docs/api/js/modules/http#httpverb
https://github.com/tauri-apps/tauri/blob/850a99a576db8b09820017890b8f49ce40e449c2/tooling/api/src/http.ts#L57

@rizwan92
Copy link

rizwan92 commented Sep 11, 2022

Hey why this thread is closed i think this is not completely resolved

My node js backend server asked for origin to resolve cors

I have added few of my development and production origin to pass cors and its working

When its comes to tauri, tauri sends request to my nginx load balancer and origin logs like

In windows origin is tauri://localhost
In mac it is "-"
In linux it is "-"

When i allow the origin in my backend tauri://localhost

Windows application is working fine

But mac and linux is still not working

@rizwan92

This comment was marked as spam.

@rizwan92
Copy link

@Laegel any support or answer or trick to bypass this issue

@psytron
Copy link

psytron commented Oct 24, 2022

Will there be a config option for this?

or flag:

  --disable-web-security

or config:

 webPreferences: {
         webSecurity: false,
  }

@rizwan92
Copy link

how to make origin request from electron like this

https://billing.chikupos.com

so i can only allow request cors for this url to secure my servers access not everyone will be able to access

@FabianLars
Copy link
Member

Will there be a config option for this?

No ( = highly unlikely)

how to make origin request from electron like this

Using the webview's native http functions it's realistically only possible on Windows: tauri-apps/tauri#4912. In Rust it should be easy tho.

@emdax
Copy link

emdax commented Nov 9, 2022

+1
Tauri is a technological marvel. Just curious what is the rationale behind this limitation?

As it stands, even a basic app which could be neatly encapsulated in one secure process, instead requires splitting into side carts and more moving parts. etc.

Why not enable running whole JS app neatly encapsulated inside browser process, with access to APIs/CORS etc?

@psytron
Copy link

psytron commented Nov 12, 2022

+1
Would be awesome to just package the whole JS app inside one process instead of spreading across sidecarts with open ports etc.

@FabianLars
Copy link
Member

Is anyone able to provide an actual example that show-cases what exact problems you're facing? Preferably issues that can not be fixed with tauri's own http module (https://tauri.app/v1/api/js/http). Thank you.

@robothot
Copy link

robothot commented Feb 5, 2023

Is anyone able to provide an actual example that show-cases what exact problems you're facing? Preferably issues that can not be fixed with tauri's own http module (https://tauri.app/v1/api/js/http). Thank you.

@FabianLars

play video, i use hls.js

there will be cross-domain problems.

because I want to play videos from other sites

example.zip

the following start project command

  1. npm install
  2. npm run start

@nathanbabcock
Copy link

@robothot I'm trying to do the exact same thing. I ended up implementing a custom loader for Hls.js that uses Tauri's HTTP Fetch instead of the default browser XHR.

https://gist.github.com/nathanbabcock/59c0298bed74ac48f7f209e30cf53b00

@ComfyFluffy
Copy link

I created a library called tauri-xhr to override the XHR with a custom XHR implementation which uses the http feature provided by tauri, thus bypassing the CORS limit.

https://www.npmjs.com/package/tauri-xhr

@yenche123
Copy link

@ComfyFluffy what is the difference with @tauri-api/api/http
It can also bypass the CORS limit.

@ComfyFluffy
Copy link

@yenche123 The main thing it does is to override the default XHR implementatiion which is implemented by the webview with a custom XHR that uses @tauri-api/api/http to fetch the data. Actually I'm using an SDK which uses XHR internally. With this I do not need to make changes to the SDK and just make it work.

@0xDevrim
Copy link

0xDevrim commented Dec 4, 2023

@FabianLars here is a scenario where this is a big letdown.

Download files to appDataDirPath say a html document. Then try to access the iframe content. Ie;

HTML:

<script>function hello() { console.log("hello tauri" }</script>

This will be blocked by protocol mismatch: http://localhost and tauri://localhost VS assets://.

I cannot just use fetch and use the response as the iframe src because that breaks all the relative paths in the html. String replace works to an extent.

I thought of adding a symlink as mentioned on discord - eg http://localhost:1420/datadir that would point to appDataDirPath which would actually bypass all CORS errors. But of course as you rightly said, cannot add the symlink inside the binary can we...

@simonhamp
Copy link
Contributor

simonhamp commented Jan 24, 2024

Is anyone able to provide an actual example that show-cases what exact problems you're facing? Preferably issues that can not be fixed with tauri's own http module (https://tauri.app/v1/api/js/http). Thank you.

A solid case for me:

I'm running most of my responses from a custom protocol, e.g. myproto://. I'm then trying to load javascript and other assets directly in the HTML response on that custom protocol (without forcing them to go through the same process), so they're using the asset:// protocol

I'm hitting CORS issues there because I can't instruct asset:// requests to Access-Control-Allow-Origin: myproto://*
and it doesn't appear to be handled for me.

@simonhamp
Copy link
Contributor

I have tried to get around this by switching to the tauri:// protocol for loading my resources and hooking into .on_web_resource_request(), but it looks like CORS steps in way before that callback gets fired :(

@simonhamp
Copy link
Contributor

Ok, I worked around it by making these asset/resource requests go through my custom protocol, but wiring it up to take a different path when the URI matches a certain pattern that I can control:

if req.uri().starts_with("myproto://localhost/_assets") {
  let path = req.uri().split_once("myproto://localhost/_assets")
      .map_or("", |(_, after)| after);

  let resource_path = app.path_resolver()
      .resolve_resource(format!("{}{}", "../src/public", path))
      .expect("failed to resolve resource");

  let mime_type = mime_guess::from_path(&resource_path)
    .first_or_octet_stream();

  let body = fs::read_to_string(resource_path)
    .map_err(|e| e.to_string())
    .unwrap()
    .as_bytes()
    .to_vec();

  return ResponseBuilder::new()
      .mimetype(mime_type.essence_str())
      .body(body);
}

The problem with this approach is the fact that I now have to maintain that code... it would be much nicer if this was handled internally to Tauri and return the appropriate HTTP response for the requested resource.

But that implies some ability to control the CORS headers 🤷🏻‍♂️

@RSDoty
Copy link

RSDoty commented Jan 25, 2024

If you don't care about safety. You can set the webview2 startup parameter --disable-web-security
In tauri.conf.json

{
  "tauri": {
    "windows": [
      {
        "fullscreen": false,
        "resizable": true,
        "title": "title",
        "width": 800,
        "height": 600,
        "additionalBrowserArgs": "--disable-web-security"
      }
    ]
  }
}

Reference: https://tauri.app/v1/api/config#windowconfig.additionalbrowserargs

@dong0926
Copy link

@RSDoty I don't seem to be able to use your plan.
When I am like you, my cmd displays an error.

failed to create webview: WebView2 error: WindowsError(Error { code: 0x8007139F, message: The state of the group or resource is not the correct state to perform the requested operation。 })

@MirazMac
Copy link

MirazMac commented Nov 1, 2024

If anyone is facing CORS issues related to media playback, i.e HLS, DASH with DRM support etc. You can use shaka-player with this custom network plugin:

https://gist.github.com/MirazMac/52ee5da091c274d82286b26a094000e5

I used dynamic import to import @tauri-apps/plugin-http, since importing it on the top level was giving me build errors with Sveltekit. In case anyone wonders about that. (Line: 85)

I modified it based on the original fetch plugin that shaka-player uses.

Using this is very simple.

import shaka from "shaka-player";
import { TauriFetchLoader } from "./TauriFetchLoader.js";

// Register the custom fetch plugin with Shaka
shaka.net.NetworkingEngine.registerScheme(
   "http",
   TauriFetchLoader.parse,
   shaka.net.NetworkingEngine.PluginPriority.PREFERRED,
   true,
  );
shaka.net.NetworkingEngine.registerScheme(
   "https",
   TauriFetchLoader.parse,
   shaka.net.NetworkingEngine.PluginPriority.PREFERRED,
   true,
  );
shaka.net.NetworkingEngine.registerScheme(
   "blob",
   TauriFetchLoader.parse,
   shaka.net.NetworkingEngine.PluginPriority.PREFERRED,
   true,
  );

Then you can use shaka-player normally. This will bypass CORS and also allow you to use forbidden headers.

Example:

const player = new shaka.Player(document.getElementById('video'));

const networkingEngine = player.getNetworkingEngine();

networkingEngine.registerRequestFilter((type, request) => {
      request.headers["Cookie"] = "Value";
});

Sorry about hijacking the thread but this has bothered me for so long and I hope this helps someone in the future.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests