GrandadEvans / Bank

This is a project to allow a user to better track their finances
GNU General Public License v3.0
0 stars 0 forks source link

Error 419 - CSRF Tokens not working #39

Closed GrandadEvans closed 2 years ago

GrandadEvans commented 2 years ago

While working on #36 discovered that submitting forms via Cypress end-to-end testing it would result in http error 419, which is the CSRF token refused. However Laravel Sanctum should solve this as it switches to cookie based authentication.

GrandadEvans commented 2 years ago

This was caused by a lack of understanding on my part. I didn't realise that cookies were cleared between tests, or should I say that I didn't realise that cookies were cleared between it() test blocks. As an example.

describe('tags.spec', () => {
    before(() => {
        cy.refreshDatabase();
        cy.create('Bank\\Models\\User')
    });

    beforeEach(() => {
        Cypress.Cookies.preserveOnce('laravel_session', 'banking_dev_session', 'XSRF-TOKEN');
    });

    it("let's us login", () => {
        cy.login();
    });

    /*
     * This test will fail, as the cookies set via the login in the previous test would have been cleared
     * after it had finished. This call to /dashboard, therefore would result in redirect back to the login
     * page.
     *
     * I don't know why the preserveOnce call in the beforeEach function doesn't work in this particular
     * example, but it doesn't
     */
    it("let's us go to dashboard after logging in", () => {
        cy.visit('/dashboard');
    });

    // the answer therefore is to group all the logic needed for one test into it's own... well... test.
    it("let's us login and visit the dashboard", () => {
        cy.login();
        cy.visit('/dashboard');
    });
});

This is a very slimmed down version of my tests, but it just illustrates that the cookies are cleared between tests.