Reputation: 770
I'm a newbie in spring Mvc, I've just done the user authentication with spring security and I want that the logged user is shown in the home page (a message like "userX is connected" ) and have a logging of all users who logged. Can you help me ? any ideas ?
Upvotes: 1
Views: 6200
Reputation: 21720
The recommended practice is to add a request attribute with the value of the username to the request. The advantage is that this decouples you from Spring Security. If you decide to remove Spring Security your view is not impacted. In Spring MVC you can populate the request attribute with something like:
@RequestMapping("/home")
public String home(Principal principal, Model model) {
if(principal != null) {
model.addAttribute("username", principal.getName());
}
}
In a standard Servlet environment (i.e. not using Spring MVC) you can simply use
if(principal != null) {
httpServletRequest.setAttribute("username", principal.getName());
}
Then in your JSP you can display it using something like this:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...
<c:out value="${username}"/>
NOTE: It is extremely important to use a tag library to output the username to avoid XSS issues. Do not use ${username} without placing it within a taglib or ensuring the value is properly escaped.
Most of the time users want to be able to add the username to every page. You can easily do this in Spring MVC 3.2+ using @ModelAttribute
& @ControllerAdvice
. For example:
@ControllerAdvice
public class UserControllerAdvice {
@ModelAttribute("username")
public String username(Principal principal) {
return principal == null ? null : principal.getName();
}
}
Spring Security exposes the user as a Principal on the standard HttpServletRequest.getUserPrincipal()
(this is actually how Principal is resolved in our Spring MVC example) and HttpServletRequest.getRemoteUser()
methods. This means you can also access the user in the JSP in the HttpServletRequest. This means you can also use:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...
<c:out value="${pageContext.request.remoteUser}"/>
An alternative is to use the Spring Security JSP tag lib (as already pointed out). For example
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<sec:authentication property="name"/>
You can log authentication attempts by implementing ApplicationListener and exposing it as a bean. Spring Security provides an implementation named LoggerListener out of the box. To use it add something like this to your configuration:
<b:bean class="org.springframework.security.authentication.event.LoggerListener"/>
You can provide your own implementation too. Here is an outline of what it would look like:
public class MyListener implements ApplicationListener<AbstractAuthenticationEvent> {
public void onApplicationEvent(AbstractAuthenticationEvent event) {
// do something
}
}
Upvotes: 8