微信公眾號(hào)授權(quán)登錄

前幾天寫了一篇《微信小程序授權(quán)登錄》的博文,今天來寫一篇關(guān)于微信公眾號(hào)授權(quán)登錄的博文。
首先需要拿到一個(gè)微信公眾號(hào)的appID和appsecret,這里在微信公眾平臺(tái)申請(qǐng)了一個(gè)測(cè)試賬號(hào)。


測(cè)試號(hào)管理.png

為了進(jìn)行公網(wǎng)的測(cè)試,運(yùn)用花生殼進(jìn)行內(nèi)網(wǎng)滲透:


花生殼..png

在公共平臺(tái)進(jìn)行網(wǎng)頁賬號(hào)設(shè)置,填寫剛才的公網(wǎng)域名進(jìn)去。


網(wǎng)頁賬號(hào)1.png
網(wǎng)頁賬號(hào)2.png

微信授權(quán)使用的是OAuth2.0授權(quán)的方式。主要有以下步驟:

  1. 用戶同意授權(quán),獲取code
  2. 通過code換取網(wǎng)頁授權(quán)access_token
  3. 刷新access_token(如果需要)
  4. 拉取用戶信息(需scope為 snsapi_userinfo)

接下來是代碼編寫:
通過appID和appsecret請(qǐng)求 open.weixin.qq.com/connect/oauth2/authorize 獲取code

@Controller
@RequestMapping("/wx")
@Slf4j
public class LoginController {

    @RequestMapping("/login")
    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String backUrl = "http://****:80/ok";
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?"
                +"appid=" + AuthUtil.APPID
                +"&redirect_uri="+ URLEncoder.encode(backUrl,"UTF-8")
                +"&response_type=code"
                +"&scope=snsapi_userinfo"
                +"&state=STATE#wechat_redict";

        response.sendRedirect(url);
    }

}

回調(diào)地址:
經(jīng)過上一步獲取的code去請(qǐng)求 api.weixin.qq.com/sns/oauth2/access_token 獲取openid和token,接著通過openid和token兩個(gè)參數(shù)去獲取用戶信息userinfo。

@RequestMapping("ok")
    public String ok(HttpServletRequest request) throws IOException {
        String code= request.getParameter("code");
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + AuthUtil.APPID
                + "&secret=" + AuthUtil.APPSECRET
                + "&code=" + code
                + "&grant_type=authorization_code";

        JSONObject jsonObject = AuthUtil.doGetJson(url);
        log.info(jsonObject.toString());
        String openid = jsonObject.getString("openid");
        String token = jsonObject.getString("access_token");

        String infoUrl = "https://api.weixin.qq.com/sns/userinfo?"
                + "access_token=" +token
                + "&openid=" + openid
                + "&lang=zh_CN";

        JSONObject uerInfo = AuthUtil.doGetJson(infoUrl);
        log.info(uerInfo.toString());

        return "ok";
    }

測(cè)試:


公網(wǎng)測(cè)試1.png
公網(wǎng)測(cè)試2.png
后臺(tái)用戶數(shù)據(jù).png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容