adam2510
adam2510

Reputation: 563

show user full name and other fields in jsp header for authenticated user

what i would like to achieve is at the bottom of the header i would like to show a few fields regarding to the authenticated user,

the fields i would like to be able to get are the ID, Location and Full name of that user

I am unsure on how to go about solving this

Thanks in advance.

Upvotes: 2

Views: 1375

Answers (2)

Christian Vielma
Christian Vielma

Reputation: 16035

I was using Maven so I had to add the taglibs library adding this to the pom.xml

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-taglibs</artifactId>
    <version>3.1.3.RELEASE</version>
</dependency>

Then in my jsp added:

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

And:

<sec:authentication property="principal" />

Upvotes: 1

esaj
esaj

Reputation: 16035

It's been quite a while since the last time I was dealing with Spring Security, but I managed to find this from an old project:

public static Object getPrincipal() 
{
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    return auth == null ? null : auth.getPrincipal();
}

I could be wrong, but I think the 'principal' this returns is the object your UserDetailsService-implementation returned when the user was logged in (probably a UserDetails-implementation). So you could get the user-information via this method and then pass it to the jsp-page for rendering. Hope this helps.

Edit: took a look at the Spring Security documentation, it seems there's a taglib available for jsp's, so you can get the information directly from Spring Security:

This tag allows access to the current Authentication object stored in the security context. It renders a property of the object directly in the JSP. So, for example, if the principal property of the Authentication is an instance of Spring Security's UserDetails object, then using <sec:authentication property="principal.username" /> will render the name of the current user.

Upvotes: 0

Related Questions