8

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?

Paulius Matulionis
  • 23,085
  • 22
  • 103
  • 143
user1555190
  • 2,803
  • 8
  • 47
  • 80

1 Answers1

15

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.

Tom
  • 26,212
  • 21
  • 100
  • 111
Fritz
  • 9,987
  • 4
  • 30
  • 49
  • Hi Gamb, thanks for that.. but thats not what i was after. I basically have my web.xml set up so that a particular url will only allow users of with certain roles. for instance... myapp/showdetails/ is protected to roles of type admin. I have other apps who can access this url if they have the roles set up.. so another app has this role set up, and they access this url.. in my controller im trying to get the user name.. thats where im stuck as i only get "annonymous user" – user1555190 Sep 17 '12 at 07:36
  • @user1555190 Oh, I see. I'll edit my answer and suggest another approach. – Fritz Sep 17 '12 at 15:38
  • Currently you can also get the user details from the WebRequest (Spring specific type of request) with the method "getUserPrincipal()" – frandevel May 09 '13 at 08:19