Spring Boot中结合Security Context渲染Thymeleaf模板为字符串
解决方案
1. 使用WebContext替代普通Context
Thymeleaf的Spring Security方言要求上下文实现IWebContext才能获取认证信息,因此在控制器中直接用WebContext替换普通Context即可解决问题。WebContext依赖当前请求的HttpServletRequest和HttpServletResponse,可直接从控制器方法参数中获取:
@Autowired private ISpringTemplateEngine templateEngine; @GetMapping("/your-api-path") public ResponseEntity<Map<String, String>> getRenderedHtml(HttpServletRequest request, HttpServletResponse response) { // 初始化业务数据 DynamicDetailInfo dynamicDetailInfo = new DynamicDetailInfo(); // ... 填充数据逻辑 // 创建WebContext,传入请求、响应、Servlet上下文及当前Locale WebContext context = new WebContext( request, response, request.getServletContext(), LocaleContextHolder.getLocale() ); context.setVariable("dynamicDetailInfo", dynamicDetailInfo); // 渲染模板片段 String html = templateEngine.process( "includes/_fragment", Collections.singleton("absenceDynamicDetail"), context ); // 返回JSON结果 return ResponseEntity.ok(Collections.singletonMap("renderedHtml", html)); }
2. 非Web环境下手动注入Security上下文
如果是在无HttpServletRequest的场景(比如定时任务、后台服务),可以手动将当前用户的认证信息注入到普通Context中:
@Autowired private ISpringTemplateEngine templateEngine; public String renderTemplateInBackground() { DynamicDetailInfo dynamicDetailInfo = new DynamicDetailInfo(); // ... 填充数据逻辑 Context context = new Context(); context.setVariable("dynamicDetailInfo", dynamicDetailInfo); // 从SecurityContextHolder获取当前认证信息并注入上下文 Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null) { context.setVariable("authentication", authentication); // 也可使用SpringSecurityDialect工具类完成注入 SpringSecurityContextUtils.setAuthentication(context, authentication); } return templateEngine.process( "includes/_fragment", Collections.singleton("absenceDynamicDetail"), context ); }
可搜索的关键词
- Thymeleaf WebContext Spring Security
- Thymeleaf sec:authorize 非Web上下文
- Thymeleaf 手动渲染模板 权限认证
- SpringSecurityDialect 上下文配置
内容的提问来源于stack exchange,提问作者Adder
相关产品推荐
相关产品推荐

