Play Framework csrf token generation in unit test

半腔热情 提交于 2019-12-13 07:41:52

问题


I have two unit tests that fails because of "[RuntimeException: Missing CSRF Token]":

running(testServer(3333, provideFakeApplication()), () -> {
    assertThat(WS.url("http://localhost:3333").get().get(3000).getStatus()
                ).isEqualTo(OK);

and

running(testServer(3333, provideFakeApplication()), HTMLUNIT, browser -> {
    browser.goTo("http://localhost:3333");
    assert....

How can I add a session with a CSRF token to the WS.url and the browser.goTo?

The tests are trying to reach a page that has a form.


回答1:


A global solution would be to use a fake application that has the CSRF filter enabled. To do that you need to modify (i.e. create a class that inherits from WithApplication and override) your provideFakeApplication() such as it creates the fake application passing in the global settings:

public abstract class TestWrapper extends WithApplication {
    public class GlobalTestSettings extends play.GlobalSettings {
        @Override
        public <T extends EssentialFilter> Class<T>[] filters() {
            return new Class[] { CSRFFilter.class };
        }
    }

    @Override
    protected FakeApplication provideFakeApplication() {
        stop(fakeApplication()); // Stop the existing fake app and start over
        Map<String, String> addConfig = new HashMap<>();
        return fakeApplication(addConfig, new GlobalTestSettings());
    }
}


来源:https://stackoverflow.com/questions/43587025/play-framework-csrf-token-generation-in-unit-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!