5

I want to get value of sec:loggedInUserInfo and attempt into a variable named user.

My code looks like this:

<sec:loggedInUserInfo field="username" /> 

<%
  def user = *value of field loggedInUserInfo *
%>

Is it possible for doing that?

Mr Zoomzoom
  • 51
  • 1
  • 3

5 Answers5

10

This is simpler and works fine for me:

<g:set var="user" value="${sec.username()}" />
Chris
  • 1,216
  • 9
  • 16
4

To assign any field of the UserDetails instance referred to by <sec:loggedInUserInfo> to a variable you can use:

<g:set var="fullName" value="${sec.loggedInUserInfo(field:'fullName')}" />

(see also Custom User Details)

martin
  • 1,185
  • 17
  • 22
2

If you want the user object in the gsp, just pass it back as part of the model map from the controller. in a controller action do

def user = springSecurityService.getCurrentUser()
render view: 'yourgsp', model: [user: user]
hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
1

I am not sure if we can use that tag directly, I couldn't find it earlier, so I have made my custom tag for this purpose

<m:userName id="${session.SPRING_SECURITY_CONTEXT?.authentication?.principal?.id}"/>

def userName = { attrs ->
Long id = attrs['id'] ? attrs['id'].toLong() : null
User user = User?.get(id);
out << user?.firstName

}

Sachin Anand
  • 428
  • 4
  • 10
0

I have created one taglib as loggedinUser which is added on gsp page as :

Welcome <g:loggedInUser/> ! 

Which is showing logged In username on top of each gsp in my project. In custom tag library my code is as follows :

def springSecurityService

def loggedInUser={
    if(springSecurityService.getPrincipal().equals("anonymousUser")){
        response.sendRedirect("${request.contextPath}/login/auth")
    }else{
        out <<"${springSecurityService.currentUser.username}"
        out << """ [${link(controller:"logout"){"Logout"}}]"""
    }
}

So it's showing on each page as : Welcome USERNAME[Logout] !

Aasif Solkar
  • 81
  • 1
  • 12