Search code examples
grailsspring-securityutf-8

Grails, Spring Security & Keycloak: Forms are submitted as ISO-8859-1 instead of UTF-8


I'm using Keycloak & Spring Security with Grails 4.0.9. with following dependencies

compile group: 'org.keycloak', name: 'keycloak-spring-security-adapter', version: '12.0.2'
compile "org.springframework.security:spring-security-config:4.2.13.RELEASE"
compile "org.springframework.security:spring-security-web:4.2.13.RELEASE"  

Any forms that I submit with special characters, ie. ä, will result as 'ö' when I print it out on a html page. The post parameters looks correctly. I also checked Grails settings in application.yml (view/gsp/encoding = utf-8).

My securityConfig looks as following:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http)
        http
            .authorizeRequests()
            .anyRequest().permitAll()
        http.csrf().disable() // disable CSRF since g:forms wouldnt work
    }

If I remove the dependencies, the form submission will work as expected. Thus, I think there is a problem with spring-security.

PS: I checked https://github.com/spring-projects/spring-boot/issues/3912 - but the problem seems to be fixed.


Solution

  • I came across the solution from https://stackoverflow.com/a/23051264/2027053 and it works. Therefore, I added the CharacterEncodingFilter in my configure method:

    import org.springframework.web.filter.CharacterEncodingFilter
    import org.springframework.security.web.csrf.CsrfFilter
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http)
    
        CharacterEncodingFilter filter = new CharacterEncodingFilter()
        filter.setEncoding("UTF-8")
        filter.setForceEncoding(true)
        http.addFilterBefore(filter,CsrfFilter.class)
    }