Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot and Thymeleaf using the #authentication utility

Using Spring Boot, the spring security starter and thymeleaf, I cannot access the #authentication utility after login (more precisely, it is null). I do not do any special configuration (assuming the starters will do that for me) and i do not include the sec: namespace in my templates (again, assuming I do not need it - all the examples I've seen so far don't need it either). I would like to call something like: {#authentication.expression('isAuthenticated()')}

For reference, here is the controller that gets called after authentication:

import java.security.Principal;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/site-admin")
public class VZSiteAdminController {

    @RequestMapping(method=RequestMethod.GET)
    public String mainScreen(Principal principal){

    return "site-admin";

    }
}
like image 1000
thomi Avatar asked Jan 15 '15 06:01

thomi


2 Answers

If you would like to access a property from the principal object you should go like this:

<div th:text="${#authentication.principal.something}">
    The value of the "name" property of the authentication object should appear here.
</div>

This post was really helpful for me because I add to a user image that was stored in the principal object:

<img th:if="${#authentication.principal.image}"
    class="img-circle" th:src="${#authentication.principal.image}"
    width="100" height="100" alt="place-holder" />
like image 80
Rogelio Blanco Avatar answered Sep 22 '22 10:09

Rogelio Blanco


Spring boot thymeleaf starter doesn't contain it, you need to add thymeleaf-extras-springsecurity3/4/5 as your dependency. https://github.com/thymeleaf/thymeleaf-extras-springsecurity

<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity5</artifactId>
    <version>3.0.4.RELEASE</version>
</dependency>
like image 41
Erlan Avatar answered Sep 21 '22 10:09

Erlan