【问题标题】:Thymeleaf authentication object is either null or empty on an error pageThymeleaf 身份验证对象在错误页面上为 null 或为空
【发布时间】:2023-04-10 20:18:11
【问题描述】:

成功登录后认证显然不为空,但在仍然登录时强制出错使认证为空。

  • Spring Boot 1.3.1
  • 百里香2.1.4
  • Thymeleaf-Spring4 2.1.4
  • Thymeleaf-Extras-SpringSecurity4

error.html(处理错误/异常的自定义错误页面)

...          
<header th:include="fragments/menu :: menu"></header>
...

menu.html(所有菜单项在错误/执行期间不显示)

 ...
 <li sec:authorize="hasAnyRole('ADMIN', 'MANAGER')">
 ...
 </li>
 ...
 <li sec:authorize="isAuthenticated()"><a id="logoff" href="#logoff">Log Off</a></li>
 ..

这是预期的行为还是我遗漏了什么?我希望身份验证对象不为空,因此我可以重新显示安全 url 链接。

【问题讨论】:

    标签: spring spring-boot thymeleaf


    【解决方案1】:

    这是 Spring Boot 的一个已知问题,甚至记录在 the documentation

    注意如果您使用最终将由过滤器处理的路径注册 ErrorPage(例如,在某些非 Spring 网络中很常见) 框架,如 Jersey 和 Wicket),那么过滤器必须是 显式注册为 ERROR 调度程序(默认 FilterRegistrationBean 不包括 ERROR 调度程序类型)。

    还有例子:

    @Bean
    public FilterRegistrationBean myFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new MyFilter());
        ...
        registration.setDispatcherTypes(EnumSet.allOf(DispatcherType.class));
        return registration;
    }
    

    另见related issue in Spring Boot tracker

    但您可以通过在application.properties 中添加以下行来更简单地从 1.3.1 开始配置它(参见 #4505):

    security.filter-dispatcher-types: ASYNC, FORWARD, INCLUDE, REQUEST, ERROR
    

    【讨论】:

    • 创建一个 FilterRegistrationBean 并覆盖默认的调度类型无助于解决问题。但是,在issue # 5638 之后,通过抑制默认的 BasicErrorController 提供了一种解决方法。到目前为止,这在 Spring Boot 1.3.1 + Thymeleaf 2.1.4 上运行良好。
    【解决方案2】:

    查看thymeleaf-extras-springsecurity github 页面。

    您应该将 SpringSecurity 方言添加到您的模板引擎:

    <bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
        <property name="additionalDialects">
            <set>
                <bean class="org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect"/>
            </set>
        </property>
    </bean>
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2016-04-01
      • 2011-09-12
      • 1970-01-01
      • 2021-12-27
      • 2020-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-02
      相关资源
      最近更新 更多