spring security get user id from DB

前端 未结 4 2059
南旧
南旧 2021-02-06 16:10

I am using spring security for authentication and successfully able to get User object (org.springframework.security.core.userdetails.User) anywhere I

4条回答
  •  情书的邮戳
    2021-02-06 16:21

    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!");
            model.setViewName("hello");
    
    
            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;
    
    @Service
    @Transactional
    public class UserServiceImpl implements UserService{
    
        @Autowired
        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.

提交回复
热议问题