后端获取当前登录用户信息

开发过程中,发现有很多地方需要获取当前登录的用户信息,比如新增、修改时候要记录创建人和更新人信息,如果每次操作都从数据库中获取用户信息,会增加不必要的开销,同时也增加数据库的压力。

方法一: 从redis中获取

本文将介绍一种从redis缓存中获取当前登录用户的信息,实现思路如下:

  • 用户登录时获取将用户数据存放在redis中,key值为userCode
  • 将userCode添加到cookie中
  • 后端获取cookie中的userCode,然后查询缓存,获取用户登录数据
实现代码如下:
  1. 存放用户信息到redis中, 并设置cookie
	/**
	 * 存放用户信息到redis中, 并设置cookie
	 * @param String username	// 用户账号
	 * @return
	 */
    public static final long SESSION_TIMEOUT = Long.parseLong(prop.getProperty("session.timeout","1440000"));
    public static final String USER_INFO = "user_info_";


    public void setUserInfoToRedis(HttpServletRequest request,String username, HttpServletResponse response){

        SysUser user = userService.selectOne(new EntityWrapper<SysUser>().eq("LOGIN_NAME", username));	//根据登录账号查询用户信息
        UserSessionModel userSessionModel = new UserSessionModel();
        userSessionModel.setUser(user);

        // 放入缓存中
        String userCode = UUIDGenerator.getUUID();	// 随机生成userCode
        String userKey = Constants.USER_INFO + userCode;
        redisUtils.set(userKey, JSON.toJSONString(userSessionModel), Constants.SESSION_TIMEOUT);

        // 将userCode放入cookie中
        Cookie cookie = new Cookie("userCode", userCode);
        cookie.setPath("/");
        cookie.setMaxAge((int) Constants.SESSION_TIMEOUT);
        response.addCookie(cookie); 

    }
  1. 从redis中获取当前登录用户信息:
	public static final String USER_INFO = "user_info_";

	@Autowired
    private HttpServletRequest request;

	@Autowired
	private RedisUtils redisUtils;
    /**
        从redis中获取当前登录用户信息
    */
    public SysUser getCurrentUser() {
        Cookie userCookie = CookieUtil.getCookie(request, "userCode");
        String userKey = Constants.USER_INFO + userCookie.getValue();
        Object userInfo = redisUtils.get(userKey);
        UserSessionModel userSessionModel = JSON.parseObject(userInfo.toString(), UserSessionModel.class);
        SysUser user = userSessionModel.getUser();
        return user;
    }

方法二: 通过Spring Security获取

Spring Security使用一个Authentication对象来描述当前用户的相关信息。SecurityContextHolder中持有的是当前用户的SecurityContext,而SecurityContext持有的是代表当前用户相关信息的Authentication的引用。这个Authentication对象不需要我们自己去创建,在与系统交互的过程中,Spring Security会自动为我们创建相应的Authentication对象,然后赋值给当前的SecurityContext。

UserDetails currentUserDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐