Springboot实现QQ授权登录

前言:主要包括qq接口调用和存储到自己的系统。

1、首先要到qq互联管理中心创建应用

审核通过以后我们,我们可以拿到appid、appkey。

回调地址一定要写对。 

2、阅读官方文档进行开发

我接入的是PC端。所以看网站文档

大体流程:

首先通过我们界面上的qq按钮-----》进入qq授权登录界面(qq提供的)-----》之后根据返回的code-----》获取access token

--------》通过access token 获取openId。这就是接入的流程。

3、页面展示

点击按钮进入qq授权界面

之后我们可以扫码或者点击自己的qq头像进入

成功绑定qq

4、代码部分(由于太多,只能部分贴出,大家可以下载)

 

配置文件部分

/**
 * @author : 徐长城
 * @des:   qq 配置信息
 * @date : 2019/8/10 10:24
 */
public class QQConfigInfo {
    /**
     * 域名
     */
    private static final String DOMAIN = "http://www.chaicp.com";

    /**
     * APPID
     */
    public static final String APPID = "101758768";

    /**
     * APPKEY
     */
    public static final String APPKEY = "a12150f76254839e2445dfc038659e4f";

    /**
     * 回调地址
     */
    public static final String BACKURL = DOMAIN+"/qq/callback";

    /**
     * 获取qq授权网页
     */
    public static final String GETQQPAGE = "https://graph.qq.com/oauth2.0/authorize";

    /**
     * 获取Access Token
     */
    public static final String GETACCESSTOKEN = "https://graph.qq.com/oauth2.0/token";

    /**
     * 获取账户OPENID
     */
    public static final String GETACCOUNTOPENID = "https://graph.qq.com/oauth2.0/me";

    /**
     * 获取账户信息
     */
    public static final String GETACCOUNTINFO = "https://graph.qq.com/user/get_user_info";
}

 Controller

@Controller
@RequestMapping("/qq")
public class LoginContoller {

    @Autowired
    private LoginService loginService;

    /**
     * 登录页
     * @return
     */
    @GetMapping("/login")
    public String loginPage(){
        return "login";
    }

    /**
     * 跳转到qq授权网页
     * @param session
     * @return
     */
    @GetMapping("/qq_login")
    public String qq(HttpSession session) {
        /**
         * 防止请求受到攻击
         */
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        session.setAttribute("state", uuid);

        String url = QQConfigInfo.GETQQPAGE+"?response_type=code" +
                "&client_id=" + QQConfigInfo.APPID +
                "&redirect_uri=" + URLEncoder.encode(QQConfigInfo.BACKURL) +
                "&state=" + uuid;
        return "redirect:" + url;
    }

    /**
     * qq回调地址
     * @param request
     * @return
     */
    @GetMapping("/callback")
    public String callback(HttpServletRequest request,ModelMap modelMap) {
        //ModelMap modelMap = new ModelMap();
        HttpSession session = request.getSession();
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        String uuid = (String) session.getAttribute("state");
        if (uuid != null) {
            if (!uuid.equals(state)) {
                System.out.println("TOKEN错误, 防止CSRF攻击, 业务异常处理......");
                return null;
            }
        }
        QQAccountInfo qqAccountInfo = null;
        try {
            qqAccountInfo =  loginService.saveQQAccount(code);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        modelMap.addAttribute("user_info",qqAccountInfo);
        return "index";
    }


}

Service

@Service
public class LoginService {

    private Gson gson = new Gson();

    @Autowired
    private QQUserDao qqUserDao;

    /**
     * 保存qq账户
     * @param code
     * @return
     * @throws Exception
     */
    public QQAccountInfo saveQQAccount(String code) throws Exception{
        // 获取access token
        String access_url = QQConfigInfo.GETACCESSTOKEN+"?grant_type=authorization_code" +
                "&client_id=" + QQConfigInfo.APPID +
                "&client_secret=" + QQConfigInfo.APPKEY +
                "&code=" + code +
                "&redirect_uri=" + QQConfigInfo.BACKURL;
        String  access_res = HttpClientUtils.httpGet(access_url);
        String access_token = "";
        if (access_res.indexOf("access_token") >= 0) {
            String[] array = access_res.split("&");
            for (String str: array)
                if (str.indexOf("access_token") >= 0) {
                    access_token = str.substring(str.indexOf("=") + 1);
                    break;
                }
        }

        // 获取qq账户 openId
        String open_id_url = QQConfigInfo.GETACCOUNTOPENID+"?access_token="+access_token;
        String open_id_res = HttpClientUtils.httpGet(open_id_url);
        int startIndex = open_id_res.indexOf("(");
        int endIndex = open_id_res.lastIndexOf(")");
        String open_id_res_str = open_id_res.substring(startIndex + 1, endIndex);
        OpenId accountOpen = gson.fromJson(open_id_res_str,OpenId.class);

        // 获取账户qq信息
        String account_info_url = QQConfigInfo.GETACCOUNTINFO+"?access_token="+access_token+
                "&oauth_consumer_key=" + QQConfigInfo.APPID +
                "&openid=" + accountOpen.getOpenid();
        String account_info_res = HttpClientUtils.httpGet(account_info_url);
        QQAccountInfo accountInfo = gson.fromJson(account_info_res,QQAccountInfo.class);
        accountInfo.setOpen_id(accountOpen.getOpenid());
        // 判断openid在系统中是否存在
        QQAccountInfo isExits = qqUserDao.getQQUserById(accountOpen.getOpenid());
        if(isExits == null){
            // 插入
            qqUserDao.addQQUser(accountInfo);
        }else {
            // 更新
            qqUserDao.updateQQUser(accountInfo);
        }
        return accountInfo;
    }
}

数据库表结构

CREATE TABLE `qq_user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `open_id` varchar(255) NOT NULL,
  `nickname` varchar(255) DEFAULT NULL,
  `gender` varchar(5) DEFAULT NULL,
  `figureurl_qq_1` varchar(255) DEFAULT NULL,
  `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

 

  • 1
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值