Spring Security Spring安全Freemarker会话为空或缺失

ni65a41a  于 2023-02-23  发布在  Spring
关注(0)|答案(1)|浏览(180)

我正在尝试使用Freemarker模板中的Session对象:

<#assign
known = Session.SPRING_SECURITY_CONTEXT??
>

<#if known>
    <#assign
    user = Session.SPRING_SECURITY_CONTEXT.authentication.principal
    name = user.getUsername()
    isAdmin = user.isAdmin()
    currentUserId = user.getId()
    >
<#else>
    <#assign
    name = "unknown"
    isAdmin = false
    currentUserId = -1
    >
</#if>

但接收到错误:

freemarker.core.InvalidReferenceException: The following has evaluated to null or missing:
==> Session  [in template "parts/security.ftlh" at line 2, column 9]

如何在Freemarker中使用Session对象?是否存在另一种基于用户角色隐藏某些HTML元素的方法?

rkue9o1l

rkue9o1l1#

spring.freemarker.expose-session-attributes=true添加到application.properties
并将代码修改为:

<#assign
    known = SPRING_SECURITY_CONTEXT??
>
    
<#if known>
    <#assign
        user = SPRING_SECURITY_CONTEXT.authentication.principal
        name = user.getUsername()
        isAdmin = user.isAdmin()
        currentUserId = user.getId()
    >
<#else>
    <#assign
        name = "unknown"
        isAdmin = false
        currentUserId = -1
    >
</#if>

相关问题