微信公众号授权登录

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

为了进行公网的测试,运用花生壳进行内网渗透:
在这里插入图片描述

在公共平台进行网页账号设置,填写刚才的公网域名进去。
在这里插入图片描述

在这里插入图片描述

微信授权使用的是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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Radom7

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值