spring security从DB获取用户ID [英] spring security get user id from DB

查看:240
本文介绍了spring security从DB获取用户ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用spring security进行身份验证,并成功获取用户对象( org.springframework.security.core.userdetails.User )我需要的任何地方。

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

但我想要 UserId ,这在春天不存在用户对象。所以我创建了自己的对象( com.app.site.pojo.User )。它没有其他变量,如 userId 用户出生日期等。现在我希望spring security使用我的用户 object而不是spring User object。它应该包含有关该用户的所有细节。

But I want UserId also, which is not there in spring's User object. So I create my own object(com.app.site.pojo.User). It has few additional variables like userId,user date of birth etc. Now I want spring security to use my user object instead of spring User 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).

我不想再次调用DB来再次从DB获取userId。

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

我怎么能实现它?

推荐答案

我和你的情况相同,我所做的是将用户重定向到登录后的新页面,并创建该页面的控制器功能,以便从DB获取用户并将 id 存储为会话变量

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;

    }

您可以使用用户对象或只使用他的 id 以便进行日后查询

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

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

我的 userService 只是一项简单的服务

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.

这篇关于spring security从DB获取用户ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆