I am using Spring MVC and Spring Security version 3.0.6.RELEASE. What is the easiest way to get the user name in my JSP? Or even just whether or not the user is logged in? I
1) MY CUSTOM USER CLASS with extra field mobile:
public class SiteUser extends User {
public SiteUser(String username, String password, Collection<? extends GrantedAuthority> authorities,
String mobile) {
super(username, password, true, true, true, true, authorities);
this.mobile = mobile;
}
private String mobile;
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
}
2) IN MY UserDetailsServiceImpl.java I POPULATED THIS CUSTOM SiteUser object.
public SiteUser loadUserByUsername(String username) {
UserInfoVO userInfoVO = userDAO.getUserInfo(username);
GrantedAuthority authority = new SimpleGrantedAuthority(userInfoVO.getRole());
SiteUser siteUser = new SiteUser(userInfoVO.getUsername(), userInfoVO.getPassword(),
Arrays.asList(authority), userInfoVO.getMobile());
return siteUser;
}
3) AND IN VIEW I AM ACCESSING IT AS:
< a href="#" th:text="${#httpServletRequest.userPrincipal.principal.mobile}">
Check Spring security tags : <sec:authentication property="principal.username" />
http://static.springsource.org/spring-security/site/docs/3.0.x/reference/taglibs.html
And you can check if logged :
<sec:authorize access="isAuthenticated()">
instead of c:if
This works whether user is logged in or not, and works when using Anonymous Authentication:
<sec:authorize access="isAuthenticated()">
<sec:authentication property="principal.username" var="username" />
</sec:authorize>
<sec:authorize access="!isAuthenticated()">
<sec:authentication property="principal" var="username" />
</sec:authorize>
Later...
Hello ${username}
For accessing a principal attribute use, first, create a variable for attributes:
<sec:authentication property="principal.attributes" var="principalAttr"/>
Then, you can use this map for retrieving values by the attribute key name:
${principalAttr.get("given_name")}
Do not forget to add spring security taglib in your maven dependencies list:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>5.3.4.RELEASE</version>
</dependency>
As far as I know by default Spring Security 3.0.x installs a SecurityContextHolderRquestAwareFilter, so that you can get the Authentication
object by calling HttpServletRequest.getUserPrincipal()
, and you can also query roles by calling HttpServletRequest.isUserInRole()
.
You can use like this: Spring Security Tag Lib - 3.1.3.RELEASE
<sec:authentication var="principal" property="principal" />
and Then:
${principal.username}