微信Oauth登录——RedirectView Flash Attributes属性分布式环境下丢失问题

最近在做微信登录功能时,微信扫码页和报错页使用同一个url页面:
http://www.test.com/oauth/wechat/login

示例代码如下:

/**
     * 发起微信oauth登录
     *
     * @return
     */
    @RequestMapping({"/wechat/login"})
    public ModelAndView oauthLogin(HttpServletRequest request, @RequestParam(required = false) String returnUrl,
                                   @ModelAttribute("message") String message, @ModelAttribute("success") String success) {
        ModelAndView modelAndView = new ModelAndView();

        String state = RandomStringUtils.randomAlphabetic(20);

        logger.info("returnUrl={}", StringEscapeUtils.escapeURL(resource.getClient().getPreEstablishedRedirectUri() + "?returnUrl=" + returnUrl));
        modelAndView.addObject("appid", resource.getClient().getClientId());
        modelAndView.addObject("redirect_uri",
                StringEscapeUtils.escapeURL(resource.getClient().getPreEstablishedRedirectUri() + "?returnUrl=" + returnUrl));
        modelAndView.addObject("state", state);
        modelAndView.addObject("scope", "snsapi_login");
        modelAndView.addObject("returnUrl", returnUrl);
        
        //设置报错信息
        if (StringUtils.isNotBlank(success)) {
            modelAndView.addObject("success", success);
            modelAndView.addObject("message", message);
        }

        modelAndView.setViewName("wechat_qr_code");
        return modelAndView;
    }
微信Oauth登录——RedirectView Flash Attributes属性分布式环境下丢失问题_第1张图片
image.png
微信Oauth登录——RedirectView Flash Attributes属性分布式环境下丢失问题_第2张图片
image.png

用户扫描二维码后,微信回调地址是:http://www.test.com/oauth/health?code=CODE&state=STATE

因此当用户登录时校验发现异常,需要重定向到微信扫描页面,并且把报错信息传输过去,最开始采用的是RedirectView Flash Attributes来传递信息:

   private ModelAndView generateLoginFailureView(RedirectAttributes attributes, String message, String returnUrl) {
         ModelAndView modelAndView = new ModelAndView();
         attributes.addFlashAttribute("message", message);
         attributes.addFlashAttribute("success", "false");
         returnUrl = StringEscapeUtils.escapeURL(StringEscapeUtils.unescapeURL(returnUrl));
         modelAndView.setView(new RedirectView("/oauth/wechat/login?returnUrl=" + returnUrl));    
         return modelAndView;
    }

出现了一个问题,有时候报错能正常显示,有时候报错无法正常显示,排查了很长时间,才发现原来是RedirectView Flash Attributes存在的问题:

Flash Attributes:
Flash attributes provide a way for one request to store attributes that are intended for use in another. This is most commonly needed when redirecting — for example, the Post-Redirect-Get pattern. Flash attributes are saved temporarily before the redirect (typically in the session) to be made available to the request after the redirect and are removed immediately.

大致含义是:

Flash属性
Flash属性为一个请求提供了一种存储属性方式,使其能在另一个请求中使用该属性。重定向时最常需要此操作,例如Post-Redirect-Get模式。 Flash属性在重定向之前(通常在会话中)被临时保存,以便在重定向之后可供请求使用,并立即被删除。

上面介绍了Flash Attributes的功能,需要注意的是该存储是在临时会话中的。这样就存在一个问题,分布式环境下,重定向存储的属性,在用户请求时可能无法获取到(多台机器的原因)。文档也对此进行了说明:

The concept of flash attributes exists in many other web frameworks and has proven to sometimes be exposed to concurrency issues. This is because, by definition, flash attributes are to be stored until the next request. However the very “next” request may not be the intended recipient but another asynchronous request (for example, polling or resource requests), in which case the flash attributes are removed too early.

大致含义是:

Flash属性的概念存在于许多其他Web框架中,并已证明有时会遇到并发问题。这是因为根据定义,闪存属性将存储到下一个请求。但是,“下一个”请求可能不是预期的接收者,而是另一个异步请求(例如,轮询或资源请求),在这种情况下,过早删除闪存属性。

对于该问题,在微信登录中,本人采用redis缓存进行解决。大致代码如下:

private ModelAndView generateLoginFailureView(RedirectAttributes attributes, String message, String returnUrl) {
         ModelAndView modelAndView = new ModelAndView();
         returnUrl = StringEscapeUtils.escapeURL(StringEscapeUtils.unescapeURL(returnUrl));
         cache.setEx(OAUTH_LOGIN_STATUS_PREFIX + state, "false|" + message, 1, TimeUnit.MINUTES);
         modelAndView.setView(new RedirectView("/oauth/wechat/login?state=" + state +"&returnUrl=" + returnUrl));  
         return modelAndView;
    }
  @RequestMapping({"/wechat/login"})
    public ModelAndView oauthLogin(HttpServletRequest request, @RequestParam(required = false) String returnUrl, @RequestParam(required = false) String state) {
        ModelAndView modelAndView = new ModelAndView();

        String newState = RandomStringUtils.randomAlphabetic(20);
        cache.setEx(OAUTH_LOGIN_STATUS_PREFIX + newState, "1", 5, TimeUnit.MINUTES);

        logger.info("returnUrl={}", StringEscapeUtils.escapeURL(resource.getClient().getPreEstablishedRedirectUri() + "?returnUrl=" + returnUrl));
        modelAndView.addObject("appid", resource.getClient().getClientId());
        modelAndView.addObject("redirect_uri",
                StringEscapeUtils.escapeURL(resource.getClient().getPreEstablishedRedirectUri() + "?returnUrl=" + returnUrl));
        modelAndView.addObject("state", newState);
        modelAndView.addObject("scope", "snsapi_login");
        modelAndView.addObject("returnUrl", returnUrl);


        if (StringUtils.isNotBlank(state) && cache.exist(OAUTH_LOGIN_STATUS_PREFIX + state)) {
            String[] stateValue = jCloudCache.get(OAUTH_LOGIN_STATUS_PREFIX + state).split("\\|");
            if (stateValue.length == 2) {
                modelAndView.addObject("success", stateValue[0]);
                modelAndView.addObject("message", stateValue[1]);
            }
            cache.del(OAUTH_LOGIN_STATUS_PREFIX + state);
        }

        modelAndView.setViewName("wechat_qr_code");
        return modelAndView;
    }

你可能感兴趣的:(微信Oauth登录——RedirectView Flash Attributes属性分布式环境下丢失问题)