Get Custom Property Of User Principal

5.6k views Asked by At

I have a custom user details object with first name part of it. Below username works, but I want something like the second to work. How can I access this custom property?

<security:authentication property="principal.username" />

<security:authentication property="principal.firstname" />
2

There are 2 answers

0
Stephen C On BEST ANSWER

I presume that you tried the above and that it didn't work.

Check your custom user details class to make sure that the capitalization of the getter and setter methods for the 'firstname' property are correct.

0
limc On

Works for me. Here's my test code:-

CustomUserDetails class

public class CustomUserDetails implements UserDetails {
    public String getFirstName() {
        return "hello";
    }

    ...
}

Custom tag in JSP

The following tag returns hello.

<security:authentication property="principal.firstName" /> 

By the way, make sure you are not putting getFirstName() into the anonymous class, because that will not work.

What I'm trying to say here is, don't do this:-

...

return new UserDetails() {
    // adding extra method here will not work
    public String getFirstName() {
        return "hello";
    }

    public String getUsername() {
        return "test";
    }

    ...    
};

... do this:-

...

// this class implements UserDetails and contains getFirstName()
CustomUserDetails csd = new CustomUserDetails();
csd.set...(...)
...

return csd;