[Libwebsockets] How to make a http-server which support cross-domain

Andy Green andy at warmcat.com
Mon Aug 2 14:26:58 CEST 2021



On 8/2/21 12:21 PM, Mr.zhang wrote:
> Dear:
>        Please tell me how  to make a http-server which support 
> cross-domain with libwebsocket.
> such as  "res.header('Access-Control-Allow-Origin " in other http 
> server. Thank you
> .header('Access-Control-Allow-Origin', '*')

You can associate static headers with a vhost, at vhost creation time.

https://libwebsockets.org/git/libwebsockets/tree/include/libwebsockets/lws-context-vhost.h#n299-301

Create a linked-list of pvos containing the header info like this (with 
whatever headers you want to go out from the vhost)

static const
struct lws_protocol_vhost_options pvo_hsbph[] = {{
	NULL, NULL, "referrer-policy:", "no-referrer"
}, {
	&pvo_hsbph[0], NULL, "x-frame-options:", "deny"
}, {
	&pvo_hsbph[1], NULL, "x-xss-protection:", "1; mode=block"
}, {
	&pvo_hsbph[2], NULL, "x-content-type-options:", "nosniff"
}, {
	&pvo_hsbph[3], NULL, "content-security-policy:",
	"default-src 'none'; img-src 'self' data: ; "
		"script-src 'self'; font-src 'self'; "
		"style-src 'self'; connect-src 'self' ws: wss:; "
		"frame-ancestors 'none'; base-uri 'none';"
		"form-action 'self';"
}};

Then set the vhost info.headers to, in the example above, &pvo_hsbph[4];

That will cause that set of headers to be added to everything served on 
the vhost.

-Andy



More information about the Libwebsockets mailing list