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

[1.x] Try to get CSRF token from cookie #242

Closed
wants to merge 3 commits into from
Closed

[1.x] Try to get CSRF token from cookie #242

wants to merge 3 commits into from

Conversation

m1guelpf
Copy link

@m1guelpf m1guelpf commented Sep 6, 2019

The Laravel skeleton was recently updated to stop explicitly setting the CSRF token on the axios client, as it can automatically get it from the XSRF-TOKEN Laravel adds by default. This PR introduces the same behavior on Echo.

@driesvints driesvints changed the title Try to get CSRF token from cookie [1.x] Try to get CSRF token from cookie Sep 6, 2019
@taylorotwell
Copy link
Member

Does this work since content of that cookie is an encrypted version of the CSRF token, not the token itself?

@m1guelpf
Copy link
Author

m1guelpf commented Sep 7, 2019

As you can see, Laravel decrypts the header here: https://github.com/laravel/framework/blob/6.x/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php#L153

The only thing needed to make this work would be to change the header name from X-CSRF to X-XSRF when sending the encrypted versiom. Will PR that later today

@taylorotwell
Copy link
Member

Honestly I'm fine not messing with this.

@mpskovvang
Copy link

I was about to submit a PR with a slightly different approach to setting the X-XSRF-TOKEN header, but realized it won't work with a SPA as the header can't be changed after constructing Pusher.

I came up with this solution, which ensures the header is always kept up-to-date:

const cookie = function (name) {
    let match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
    return (match ? decodeURIComponent(match[3]) : null);
}

const xsrf = (urlmatch) => {
    let open = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.open = function (method, url) {
        open.apply(this, arguments);

        if ((new URL(url, window.location)).toString().includes(urlmatch)) {
            this.setRequestHeader('X-XSRF-TOKEN', cookie('XSRF-TOKEN'))
        }
    }
};

xsrf('https://example.org/broadcasting/auth')

new Echo(...)

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

Successfully merging this pull request may close these issues.

3 participants