有没有人知道freemarker标签来检查freemarker文件中的spring安全角色和用户名?
我从网上的几个资源中发现以下代码将打印登录的用户名。但它不是打印用户名,而是打印“登录为”
<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>
希望这可以帮助。
我正在使用Maven / Jetty设置,Spring Security Tags不会自动放入WEB-INF / lib。因此,需要进行以下调整:
<#assign security=JspTaglibs[ "/WEB-INF/security.tld" ]>
或<#assign security=JspTaglibs[ "/security.tld" ]>
,具体取决于您的Web根目录。您可以创建一个可以在上下文中注入用户的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>