请求属性
推荐的做法是在请求中添加一个带有用户名值的请求属性。优点是这使您与 Spring Security 分离。如果您决定删除 Spring Security,您的视图不会受到影响。在 Spring MVC 中,您可以使用以下内容填充请求属性:
@RequestMapping("/home")
public String home(Principal principal, Model model) {
if(principal != null) {
model.addAttribute("username", principal.getName());
}
}
在标准的 Servlet 环境中(即不使用 Spring MVC)你可以简单地使用
if(principal != null) {
httpServletRequest.setAttribute("username", principal.getName());
}
然后在您的 JSP 中,您可以使用以下方式显示它:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...
<c:out value="${username}"/>
注意:使用标签库输出用户名以避免XSS问题非常重要。不要在未将 ${username} 放置在 taglib 中或确保正确转义值的情况下使用它。
大多数时候,用户希望能够将用户名添加到每个页面。您可以使用 @ModelAttribute & @ControllerAdvice 在 Spring MVC 3.2+ 中轻松完成此操作。例如:
@ControllerAdvice
public class UserControllerAdvice {
@ModelAttribute("username")
public String username(Principal principal) {
return principal == null ? null : principal.getName();
}
}
从 HttpServletRequest 访问
Spring Security 在标准 HttpServletRequest.getUserPrincipal()(这实际上是我们的 Spring MVC 示例中解析 Principal 的方式)和 HttpServletRequest.getRemoteUser() 方法中将用户公开为 Principal。这意味着您还可以在 HttpServletRequest 中访问 JSP 中的用户。这意味着您还可以使用:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...
<c:out value="${pageContext.request.remoteUser}"/>
Spring 安全标签库
另一种方法是使用Spring Security JSP tag lib(如前所述)。例如
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<sec:authentication property="name"/>
记录身份验证尝试
您可以通过实现 ApplicationListener 并将其公开为 bean 来记录身份验证尝试。 Spring Security 提供了一个开箱即用的名为 LoggerListener 的实现。要使用它,请在您的配置中添加如下内容:
<b:bean class="org.springframework.security.authentication.event.LoggerListener"/>
您也可以提供自己的实现。以下是它的外观轮廓:
public class MyListener implements ApplicationListener<AbstractAuthenticationEvent> {
public void onApplicationEvent(AbstractAuthenticationEvent event) {
// do something
}
}