How can I set Websocket Origin Header in react-native?

1k views Asked by At

I want to change Origin Header of the websocket handshake in react native.

like this

var ws = new WebSocket(
    'http://localhost/auth',
    [],
    {
        'headers': {
            'Origin': "https://secret-host.com"
        }
    }
);

I also tried react-native ios websocket library directly.

from

CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Origin"), (__bridge CFStringRef)_url.RCTSR_origin);

to

CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Origin"), CFSTR("https://secret-host.com"));

https://github.com/facebook/react-native/blob/1e8f3b11027fe0a7514b4fc97d0798d3c64bc895/Libraries/WebSocket/RCTSRWebSocket.m#L468

But it can't work.

Does anyone know how to change it? I need this for using skyway(WebRTC) in react-native.

Thanks.

1

There are 1 answers

0
Seph Soliman On

Your proposed approach should actually work in React Native 0.68.* and higher:

var ws = new WebSocket(
    'http://localhost/auth',
    undefined,
    {
        headers: {
            Origin: 'https://secret-host.com',
            Authorization: 'Bearer ***'
        }
    }
);

The caveat is that it always adds an origin header, so you cannot remove it without patching RN itself (which is doable using patch-package). This is the code you were referring to - it always generates a default Origin: header. You can set it to Origin: "" but it will still be sent which may not be good enough for your server.

On later lines in the linked RN code, it's being overwritten by your custom JS value in an "enumeration"/loop which is why your code should work.

To check if the header is being set, you can add a breakpoint in that file you linked on line 483 ([self _readHTTPHeader];) in Xcode and when the socket connects, add a watch for the following code:

[[NSString alloc] initWithData:message encoding:NSUTF8StringEncoding];

Then right click the watched value and click "Print description": enter image description here

You should see the actual output of the HTTP request, which will be something like this:

GET /auth
Host: localhost
Sec-WebSocket-Key: eHh4YWJjZGVmZ2hpamts
Sec-WebSocket-Version: 13
Upgrade: websocket
Origin: https://secret-host.com
Connection: Upgrade