使用 #authentication 实用程序的 Spring Boot 和 Thymeleaf

tho*_*omi 5 java spring-security thymeleaf spring-boot

使用 Spring Boot、spring security starter 和 thymeleaf,登录后我无法访问 #authentication 实用程序(更准确地说,它为空)。我没有做任何特殊的配置(假设初学者会为我做这件事)并且我没有在我的模板中包含 sec: 命名空间(同样,假设我不需要它 - 到目前为止我看到的所有例子都没有)也不需要)。我想这样称呼:{#authentication.expression('isAuthenticated()')}

作为参考,这是在身份验证后调用的控制器:

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";

    }
}
Run Code Online (Sandbox Code Playgroud)

Rog*_*nco 7

如果你想从主体对象访问一个属性,你应该像这样:

<div th:text="${#authentication.principal.something}">
    The value of the "name" property of the authentication object should appear here.
</div>
Run Code Online (Sandbox Code Playgroud)

这篇文章对我很有帮助,因为我添加了一个存储在主体对象中的用户图像:

<img th:if="${#authentication.principal.image}"
    class="img-circle" th:src="${#authentication.principal.image}"
    width="100" height="100" alt="place-holder" />
Run Code Online (Sandbox Code Playgroud)


Erl*_*lan 6

Spring boot thymeleaf starter 不包含它,您需要添加 thymeleaf-extras-springsecurity3/4/5 作为您的依赖项。 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>
Run Code Online (Sandbox Code Playgroud)