Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Spring How to print user first name and last name from "<sec:authentication property="principal.username"/>"

How to print user first name and last name from <sec:authentication property="principal.username"/>

This principal.username only prints user Id. But I want here to print the user first and last name from database. Is it possible?

like image 679
ajit Avatar asked Jun 25 '13 12:06

ajit


1 Answers

I guess you are talking about Spring Security.

Here is a solution I used:

Create a class that will map your users. It have to implements the interface org.springframework.security.core.userdetails.UserDetails :

public class MyUserDetails implements UserDetails {
    private String username;
    private String password;

    private String firstname;
    private String lastname;

    public String getFirstname() {
        return firstname;
    }

    public String getLastname() {
        return lastname;
    }

    // Etc.
}

Create an implementation of org.springframework.security.core.userdetails.UserDetailsService that will load your users from the database :

@Component
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private MyUserDAO userDAO;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        final MyUserDetails user = userDAO.getUserByUsername(username);
        if(user == null) {
            throw new UsernameNotFoundException("No user found for username '" + username +"'.");
        }
        return user;
    }
}

Now you have to tell Spring Security to use your service to load the details from your users :

<authentication-manager>
    <user-service id="myUserDetailsService"/>
</authentication-manager>

Now you should be able to use <sec:authentication property="principal.firstname"/> and <sec:authentication property="principal.lastname"/> to display the firstname and the lastname of the current user.

like image 124
Raphaël Avatar answered Oct 01 '22 02:10

Raphaël