微信Oauth登錄——RedirectView Flash Attributes屬性分布式環(huán)境下丟失問題

最近在做微信登錄功能時(shí)式塌,微信掃碼頁和報(bào)錯(cuò)頁使用同一個(gè)url頁面:
http://www.test.com/oauth/wechat/login

示例代碼如下:

/**
     * 發(fā)起微信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);
        
        //設(shè)置報(bào)錯(cuò)信息
        if (StringUtils.isNotBlank(success)) {
            modelAndView.addObject("success", success);
            modelAndView.addObject("message", message);
        }

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

用戶掃描二維碼后捂敌,微信回調(diào)地址是:http://www.test.com/oauth/health?code=CODE&state=STATE

因此當(dāng)用戶登錄時(shí)校驗(yàn)發(fā)現(xiàn)異常泛烙,需要重定向到微信掃描頁面叹谁,并且把報(bào)錯(cuò)信息傳輸過去矢腻,最開始采用的是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;
    }

出現(xiàn)了一個(gè)問題瓶殃,有時(shí)候報(bào)錯(cuò)能正常顯示敲茄,有時(shí)候報(bào)錯(cuò)無法正常顯示位谋,排查了很長時(shí)間,才發(fā)現(xiàn)原來是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屬性為一個(gè)請(qǐng)求提供了一種存儲(chǔ)屬性方式堰燎,使其能在另一個(gè)請(qǐng)求中使用該屬性掏父。重定向時(shí)最常需要此操作,例如Post-Redirect-Get模式秆剪。 Flash屬性在重定向之前(通常在會(huì)話中)被臨時(shí)保存赊淑,以便在重定向之后可供請(qǐng)求使用,并立即被刪除仅讽。

上面介紹了Flash Attributes的功能陶缺,需要注意的是該存儲(chǔ)是在臨時(shí)會(huì)話中的。這樣就存在一個(gè)問題洁灵,分布式環(huán)境下饱岸,重定向存儲(chǔ)的屬性,在用戶請(qǐng)求時(shí)可能無法獲取到(多臺(tái)機(jī)器的原因)徽千。文檔也對(duì)此進(jìn)行了說明:

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框架中苫费,并已證明有時(shí)會(huì)遇到并發(fā)問題。這是因?yàn)楦鶕?jù)定義双抽,閃存屬性將存儲(chǔ)到下一個(gè)請(qǐng)求百框。但是,“下一個(gè)”請(qǐng)求可能不是預(yù)期的接收者牍汹,而是另一個(gè)異步請(qǐng)求(例如铐维,輪詢或資源請(qǐng)求)柬泽,在這種情況下,過早刪除閃存屬性方椎。

對(duì)于該問題聂抢,在微信登錄中,本人采用redis緩存進(jìn)行解決棠众。大致代碼如下:

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;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末琳疏,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子闸拿,更是在濱河造成了極大的恐慌空盼,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,284評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件新荤,死亡現(xiàn)場(chǎng)離奇詭異揽趾,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)苛骨,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門篱瞎,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人痒芝,你說我怎么就攤上這事俐筋。” “怎么了严衬?”我有些...
    開封第一講書人閱讀 164,614評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵澄者,是天一觀的道長。 經(jīng)常有香客問我请琳,道長粱挡,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,671評(píng)論 1 293
  • 正文 為了忘掉前任俄精,我火速辦了婚禮询筏,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘竖慧。我一直安慰自己屈留,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,699評(píng)論 6 392
  • 文/花漫 我一把揭開白布测蘑。 她就那樣靜靜地躺著,像睡著了一般康二。 火紅的嫁衣襯著肌膚如雪碳胳。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,562評(píng)論 1 305
  • 那天沫勿,我揣著相機(jī)與錄音挨约,去河邊找鬼味混。 笑死,一個(gè)胖子當(dāng)著我的面吹牛诫惭,可吹牛的內(nèi)容都是我干的翁锡。 我是一名探鬼主播,決...
    沈念sama閱讀 40,309評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼夕土,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼馆衔!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起怨绣,我...
    開封第一講書人閱讀 39,223評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤角溃,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后篮撑,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體减细,經(jīng)...
    沈念sama閱讀 45,668評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,859評(píng)論 3 336
  • 正文 我和宋清朗相戀三年赢笨,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了未蝌。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,981評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡茧妒,死狀恐怖萧吠,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情嘶伟,我是刑警寧澤怎憋,帶...
    沈念sama閱讀 35,705評(píng)論 5 347
  • 正文 年R本政府宣布蝴簇,位于F島的核電站惠豺,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏璃岳。R本人自食惡果不足惜铸鹰,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,310評(píng)論 3 330
  • 文/蒙蒙 一癌别、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧蹋笼,春花似錦展姐、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,904評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至逊谋,卻和暖如春擂达,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背胶滋。 一陣腳步聲響...
    開封第一講書人閱讀 33,023評(píng)論 1 270
  • 我被黑心中介騙來泰國打工板鬓, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留悲敷,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,146評(píng)論 3 370
  • 正文 我出身青樓俭令,卻偏偏與公主長得像后德,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子抄腔,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,933評(píng)論 2 355