正在检查Freemarker模板中的Spring安全角色和登录的用户名



有人知道在freemarker文件中检查spring安全角色和用户名的freemarker标记吗

我从网上的一些资源中发现,下面的代码将打印登录的用户名。但它并没有打印用户名,而是打印"登录为"

<security:authorize access="isAuthenticated()">
    logged in as <security:authentication property="principal.username" /> 
</security:authorize>

此外,检查Freemarker文件中的角色也不起作用。以前有人做过吗?

以下操作应该有效:
步骤1:在freemarker文件的顶部包含Spring安全标记库
<#assign security=JspTaglibs["http://www.springframework.org/security/tags"] />

步骤2:检查角色名称

<@security.authorize ifAnyGranted="ROLE_USER">
    Your role is "ROLE_USER" <br/>
</@security.authorize>

步骤3:检查登录用户的登录名

<@security.authorize access="isAuthenticated()">
    logged in as <@security.authentication property="principal.username" /> 
</@security.authorize>
<@security.authorize access="! isAuthenticated()">
    Not logged in
</@security.authorize>

希望这能有所帮助。

您可以创建一个HandlerInterceptor,它可以在上下文中注入用户:

public class PutUserInModelInterceptor implements HandlerInterceptor {
  @Override
  public boolean preHandle(HttpServletRequest aRequest, HttpServletResponse aResponse, Object aHandler) throws Exception {
    return true;
  }
  @Override
  public void postHandle(HttpServletRequest aRequest, HttpServletResponse aResponse, Object aHandler, ModelAndView aModelAndView) throws Exception {
    if(aModelAndView != null) {
      Principal user = aRequest.getUserPrincipal();
      aModelAndView.addObject("__user", user);
    }
  }
  @Override
  public void afterCompletion(HttpServletRequest aRequest, HttpServletResponse aResponse, Object aHandler, Exception aEx) throws Exception { }
}

然后注册:

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new PutUserInModelInterceptor());
  }
}

然后在模板中使用它。例如:

<#if !(__user??)> 
  <a class="p-2" href="#" data-toggle="modal" data-target="#signinModal">Sign in</a>
<#else>
  <span class="badge badge-secondary">${__user.getName()}</span>
</#if>

我使用的是Maven/JJetty设置,Spring安全标签不会自动放入WEB-INF/lib中。因此,需要进行以下调整:

  1. 根据您的web根目录,使用以下作业:<#assign security=JspTaglibs[ "/WEB-INF/security.tld" ]><#assign security=JspTaglibs[ "/security.tld" ]>
  2. 非常难看:将security.tld从spring security taglibs jar复制到WEB-INF中。不幸的是,我无法让Freemarker从类路径解析标签库

最新更新