Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring security sessionscope appears to be null when using Thymeleaf

When login fails with spring security, it throws exception and it displays it in my JSP like this:

<c:if test="${not empty error}">
    <div class="errorblock">
        Your login attempt was not successful, try again.<br /> Caused :
        ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
    </div>
</c:if>

Now I am changing from JSP to Thymeleaf and trying to do the same thing, but when log in fails, the sessionScope variable seems to be null.

<div th:if="${error}" class="errorblock" th:text="'testing ' + ${sessionScope}">

</div>

This prints out testing null . When I change view resolver back to JSP, it works nicely. I think I am doing something wrong. Any suggestions?

like image 394
Jaanus Avatar asked Nov 29 '22 08:11

Jaanus


2 Answers

In Thymeleaf, you don't access session variables using the sessionScope token name. You use session instead. So you need to do something like:

<div class="error" 
     th:if="${param.login_error}"
     th:with="errorMsg=${session["SPRING_SECURITY_LAST_EXCEPTION"].message}">
  Your login attempt was not successful, try again.<br />
  Reason: <span th:text="${errorMsg}">Wrong input!</span> 
</div>

Disclaimer, according to StackOverflow rules: I am the author of Thymeleaf.

like image 140
Daniel Fernández Avatar answered Jan 21 '23 10:01

Daniel Fernández


The second isn't the same as the first. I'm not sure what you're supposed to get if you invoke the implicit EL variable sessionScope without a variable name. How about:

${sessionScope.SPRING_SECURITY_LAST_EXCEPTION.message}

Besides, are you sure your page joined the session? In JSP there's the session directive that controls whether the session scope is available through EL or not.

<%@ page session="false|true" %>
like image 43
Marcel Stör Avatar answered Jan 21 '23 10:01

Marcel Stör