user3035305 user3035305 - 1 year ago 416
Java Question

spring security get user id from DB

I am using spring security for authentication and successfully able to get

object (
) anywhere I need.

But I want
also, which is not there in spring's
object. So I create my own object(
). It has few additional variables like userId,user date of birth etc. Now I want spring security to use my
object instead of spring
object. and it should have all the details about that user.

I tried to type cast the user object to my object, it is throwing exception (It is obvious).

I dont want to make DB call again to get the userId from DB again.

How can I achieve it?

Answer Source

I was in the same situation as you, what I did was redirect the user to a new page after login, and create a controller function of that page, to get the user from DB and store his id as a Session Variable.

    @RequestMapping(value = { "/overview" }, method = RequestMethod.GET)
    public ModelAndView overViewPage(HttpServletRequest request) {

        ModelAndView model = new ModelAndView();
        model.addObject("title", "Spring Security + Hibernate Example");
        model.addObject("message", "This is default page!");

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        UserDetails userDetail = (UserDetails) auth.getPrincipal();

        User u = userService.getUser(userDetail.getUsername());
        request.getSession().setAttribute("userId", u.getId());

        return model;


You can use the user object or just use his id for future queries by doing

int userId = (int) request.getSession().getAttribute("userId");

My userService is just a simple service

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sports.dao.UserDao;

public class UserServiceImpl implements UserService{

    private UserDao userDao;

    public com.sports.models.User getUser(String username){
        return userDao.findByUserName(username);


I'm also new to spring so I'm not sure if this is the best way to do it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download