Search code examples
angularcsrfjsdata

How do I configure JSData with cookie-based sessions and CSRF headers?


I need to set up my JSData configuration to pass along info for cookie-based session authentication, as well as CSRF headers.


Solution

  • When instantiating the HttpAdapter, use the following to set withCredentials (read more) and the CSRF header (example below sets the X-CSRFToken header, but that's specific to the server-side framework; it might be something else in others' cases).

    const adapter = new HttpAdapter({
        ...
        httpConfig: {
            withCredentials: true // send cookie-based session credentials
        },
        ...
        beforeHTTP: function(config, opts) {
            ...
            config.headers || (config.headers = {});
            config.headers['X-CSRFToken'] = token;
            ...
            return HttpAdapter.prototype.beforeHTTP.call(this, config, opts);
        }
    })
    

    Getting the value for token can be done in different ways, e.g. basic version, Angular 2+ version, etc.