zgaw87
zgaw87

Reputation: 11

Access the current logged in user username with spring security in the view

How can I access the current logged in user username with springSecurity in the gsp view, or more specifically, use this value in a textfield?

This solution below doesn't work:

value="${sec.loggedInUserInfo(field:'username')}"

Upvotes: 1

Views: 4394

Answers (2)

Tyler Rafferty
Tyler Rafferty

Reputation: 3428

Custom Taglib Option to get various information about the logged in the user into the view.

ExamplNameTagLib.groovy

class ExamplNameTagLib {

   static namespace = 'foo'

   def springSecurityService


   def currentUserProps = { attrs ->
      def user = springSecurityService.getCurrentUser()
      if (user) {
         if (attrs.username) {
             out << user.username 
         } else if (attrs.firstName) {
             out << user.firstName
         } else if (attrs.lastName) {
             out << user.lastName
         } else if (attrs.email) {
             out << user.email
         }
      }
   }
}

exampleViewPage.gsp

//Return username from taglib of the logged in user
<g:field type="text" 
         name="username" 
         value="${foo.currentUserProps(username: true)}" />

//Return email from taglib of the logged in user
<g:field type="email" 
         name="email" 
         value="${foo.currentUserProps(email: true)}"/>

Upvotes: 0

Meam
Meam

Reputation: 266

The following lines both work correctly in my test.

<input name="username" type="text" value="${sec.username()}" />
<input name="username" type="text" value="${sec.loggedInUserInfo(field: 'username')}" />

Error you've got might be from other place. Could you test by only use that input tag in GSP?

Upvotes: 6

Related Questions