title: Use Spring Security in Thymeleaf escaped expressions in JavaScript
body: <p>This is possible with <code>Thymeleaf</code> 3.0:</p>
  
  <pre><code>/*[# th:if="${user.admin}"]*/
      alert('Welcome admin');
  /*[/]*/
  </code></pre>
  
  <p>However this does not work:</p>
  
  <pre><code>/*[# sec:authorize="hasAnyRole('ROLE_ADMIN)"]*/
      alert('Welcome admin');
  /*[/]*/
  </code></pre>
  
  <p>Is that really not possible or am I doing something wrong?</p>
  
  <p>I use Spring Security 4.1.</p>
  
  <p>Some background information about escaped expression parsing: <a href="https://github.com/thymeleaf/thymeleaf/issues/395" rel="nofollow noreferrer">https://github.com/thymeleaf/thymeleaf/issues/395</a></p>
  
  <p><strong>Edit 1</strong></p>
  
  <p>Daniel Fernández found a missing single quote in my initial question.</p>
  
  <p>Unfortulately after adding it, it still does not work.</p>
  
  <p>The expression is parsed, since it disappears from the resulting html/javascript.</p>
  
  <p>But document.writeln() is executed even I am not logged in, or even when I am logged in and I change the check to <code>sec:authorize="hasRole('ROLE_ADMIN123')</code></p>
  
  <pre><code>&lt;script type="text/javascript" th:inline="javascript"&gt;
  
      /*[# sec:authorize="hasRole('ROLE_ADMIN')"]*/
          document.writeln("ADMIN !!!");
      /*[/]*/
  
  &lt;/script&gt;
  </code></pre>
  
  <p><strong>Edit 2</strong></p>
  
  <p>This is my workaround <a href="https://github.com/thymeleaf/thymeleaf-extras-springsecurity/issues/42" rel="nofollow noreferrer">until further notice</a>:</p>
  
  <p>Create a method in a <code>@Service</code> which does check whether the user has the needed role(s) or not:</p>
  
  <pre><code>import javax.servlet.http.HttpServletRequest;
  import org.springframework.stereotype.Service;
  
  @Service
  public class UtilService {
  
      public boolean hasAnyRole(HttpServletRequest req, String... roles) {
          for (final String role : roles) {
              if (req.isUserInRole(role)) {
                  return true;
              }
          }
          return false;
      }
  
  }
  </code></pre>
  
  <p>And use it like this in the <code>JavaScript</code> block:</p>
  
  <pre><code>&lt;script type="text/javascript" th:inline="javascript"&gt;
  
      /*[# th:if="${@utilService.hasAnyRole(#httpServletRequest, 'ROLE_ADMIN')}"]*/
          ...
      /*[/]*/
  
  &lt;/script&gt;
  </code></pre>