微信公众号授权登录

前几天写了一篇《微信小程序授权登录》的博文,今天来写一篇关于微信公众号授权登录的博文。
首先需要拿到一个微信公众号的appID和appsecret,这里在微信公众平台申请了一个测试账号。


测试号管理.png

为了进行公网的测试,运用花生壳进行内网渗透:


花生壳..png

在公共平台进行网页账号设置,填写刚才的公网域名进去。


网页账号1.png
网页账号2.png

微信授权使用的是OAuth2.0授权的方式。主要有以下步骤:

  1. 用户同意授权,获取code
  2. 通过code换取网页授权access_token
  3. 刷新access_token(如果需要)
  4. 拉取用户信息(需scope为 snsapi_userinfo)

接下来是代码编写:
通过appID和appsecret请求 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);
    }

}

回调地址:
经过上一步获取的code去请求 api.weixin.qq.com/sns/oauth2/access_token 获取openid和token,接着通过openid和token两个参数去获取用户信息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";
    }

测试:


公网测试1.png
公网测试2.png
后台用户数据.png

你可能感兴趣的:(微信公众号授权登录)