Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC get current logged in user

My app only allows access if the current user is a specific type, this also means the role they have can log into other applications and then access certain parts of my app with specific roles, for example, my web app is configured that

<security-role> 
   <role-name>teamb</role-name>       
</security-role>

Now what I need is to be able access the details regarding this role in my app, ie.e user name

how can I do this in my Spring MVC app?

like image 634
user1555190 Avatar asked Sep 14 '12 15:09

user1555190


1 Answers

First of all, include the corresponding tag library in your pages (I'll make an example using JSP)

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

Then you just have to use those tags to query for permissions and of course, the data.

To see if an user has enough privileges for something:

<sec:authorize ifAllGranted="ROLE_ADMIN">
    <a href="page.htm">Some Admin Stuff</a>
</sec:authorize>

If the user has enough privileges, the link to page.htm will be rendered.

To get the username use ${SPRING_SECURITY_LAST_USERNAME}. Here's a logout link as an example:

<a href="<c:url value="/j_spring_security_logout" />">Logout <c:out value="${SPRING_SECURITY_LAST_USERNAME}"/></a>

Edit

To query the currently authenticated user you can try different approaches:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String username = authentication.getName();

or

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
User user = (User)authentication.getPrincipal();
user.getUsername();

Just remember to check if authentication is not null before invoking the getName or getPrincipal methods.

like image 162
Fritz Avatar answered Oct 26 '22 17:10

Fritz