domix / jade4j-spring-boot-starter

Spring Boot jade4j Starter
Apache License 2.0
64 stars 20 forks source link

Missing request attributes in ViewResolver #11

Open freswa opened 8 years ago

freswa commented 8 years ago

First of all: Thx for maintaining this project. Coming from ruby I really love this markup 👍

Whats expected:

form(name='login', action='#{contextPath}/', method='POST')
    input(type='hidden', name="#{_csrf.parameterName}", value="#{_csrf.token}")

This view should contain the csrf token and the context path.

What actually happens:

All variables are replaced with "0", like:

form(name='login', action='0/', method='POST')
    input(type='hidden', name="0", value="0")

This seems to be related to #4 and to this stackoverflow post: http://stackoverflow.com/questions/31418038/spring-boot-csrf-and-jade

thar0x29a commented 6 years ago

This is a working workaround taken from stack overflow:

@Configuration
@EnableAutoConfiguration
public class MvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(csrfTokenAddingInterceptor());
    }

    @Bean
    public HandlerInterceptor csrfTokenAddingInterceptor() {
        return new HandlerInterceptorAdapter() {
            @Override
            public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView view) {
                CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
                if (token != null) {
                    view.addObject(token.getParameterName(), token);
                }
            }
        };
    }
}

After this, you can use

input(type="hidden", name='#{_csrf.parameterName}', value='#{_csrf.token}')

to handle your csrf matters.