基於Vue、Springboot網站實現第三方登錄之QQ登錄,以及郵件發送



前言

今天將基於Vue、Springboot實現第三方登錄之QQ登錄,以及QQ郵件發送給完成了,分享出來給大家~


提示:以下是本篇文章正文內容,下面案例可供參考

一、前提(准備)

要實現QQ登錄這個功能呢,首先你得擁有一個備案好了的域名,然后前往QQ互聯注冊成為開發者,
傳送門QQ互聯
在這里插入圖片描述

審核通過之后呢,按照提示,創建一個網站應用,
在這里插入圖片描述
在這里插入圖片描述

注意PS:上圖中的網站地址信息務必要和你的網站對應的信息相符合,否則是無法審核通過的哦~

在這里插入圖片描述
創建完成后等待審核通過,比如我的:
在這里插入圖片描述

進行下一步~~

要實現QQ郵件發送呢,首先登錄你的QQ郵箱,這里是傳送門:

QQ郵箱登錄

進入QQ郵箱頁面,點擊設置,選擇賬戶,如下圖:
在這里插入圖片描述
在這里插入圖片描述

准備工作完成!

二、QQ登錄實現

1.前端

這里只貼相關代碼,頁面部分如下:

	  <!-- 第三方登錄 -->
      <el-divider>第三方登錄</el-divider>
      <div>
        <a class="icon-qq" @click="LoginClick('qq')" href="javascript:void(0);">
          <svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-QQ"></use></svg></a>
      </div>

methods中的代碼如下:

	 // 第三方登錄
    LoginClick(value) {
      if (value == "qq") {
        var _this = this;
        this.$axios.get('/qq/oauth').then(resp =>{
          //window.open(resp.data.result, "_blank")
         var width = width || 900;
            var height = height || 540;
                	var left = (window.screen.width - width) / 2;
                	var top = (window.screen.height - height) / 2;
                	var win =window.open(resp.data.result, "_blank",
                		"toolbar=yes, location=yes, directories=no, status=no, menubar=yes, scrollbars=yes, resizable=no, copyhistory=yes, left=" +
                		left + ", top=" + top + ", width=" + width + ", height=" + height);
               //監聽登錄窗口是否關閉,登錄成功后 后端返回關閉窗口的代碼
               var listener=setInterval(function(){
                  //監聽窗口是否關閉
                  if(win.closed){
                    //進入這個if代表后端驗證成功!直接跳轉路由
                    clearInterval(listener);//關閉監聽
                    //跳轉路由
                    var path = _this.$route.query.redirect;
                    _this.$router.replace({
                      path:
                        path === "/" || path === undefined ? "/admin/dashboard" : path
                    });
                    _this.$router.go(0) //刷新
                  }
                },500)

        }).catch(fail =>{
          console.error(fail)
        })
      } 
    },

上述代碼中,由 @click=“LoginClick(‘qq’)” 觸發事件,像后端發送請求,響應成功后,獲取響應回來的數據 resp.data.result 通過window.open()方法,在當前頁面再打開一個窗口。效果大致如下:
在這里插入圖片描述
為什么能顯示這樣效果呢?下面我們來看后端springboot代碼~~

2.后端

導入所需依賴:

<!-- QQ第三方登錄所需 -->
		<!--httpclient-->
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version> 4.5.9 </version>
		</dependency>
		<dependency>
			<groupId>net.gplatform</groupId>
			<artifactId>Sdk4J</artifactId>
			<version>2.0</version>
		</dependency>

1.application.yml 和工具類QQHttpClient

代碼如下:

qq:
  oauth:
    http: http://www.wangxingjun.top/ #QQ互聯中填寫的網站地址

下面編寫工具類 QQHttpClient,注意看注釋,完整代碼如下:

package top.wangxingjun.separate.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/** * @author wxj * QQ工具類(主要用於解析QQ返回的信息) */
public class QQHttpClient {
    //QQ互聯中提供的 appid 和 appkey
    public static final String APPID = "qq互聯創建的應用AppID";

    public static final String APPKEY = "qq互聯創建的應用Appkey";

    private static JSONObject parseJSONP(String jsonp){
        int startIndex = jsonp.indexOf("(");
        int endIndex = jsonp.lastIndexOf(")");

        String json = jsonp.substring(startIndex + 1,endIndex);

        return JSONObject.parseObject(json);
    }
    //qq返回信息:access_token=FE04************************CCE2&expires_in=7776000&refresh_token=88E4************************BE14
    public static String getAccessToken(String url) throws IOException {
        CloseableHttpClient client = HttpClients.createDefault();
        String token = null;

        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();

        if(entity != null){
            String result = EntityUtils.toString(entity,"UTF-8");
            if(result.indexOf("access_token") >= 0){
                String[] array = result.split("&");
                for (String str : array){
                    if(str.indexOf("access_token") >= 0){
                        token = str.substring(str.indexOf("=") + 1);
                        break;
                    }
                }
            }
        }

        httpGet.releaseConnection();
        return token;
    }
    //qq返回信息:callback( {"client_id":"YOUR_APPID","openid":"YOUR_OPENID"} ); 需要用到上面自己定義的解析方法parseJSONP
    public static String getOpenID(String url) throws IOException {
        JSONObject jsonObject = null;
        CloseableHttpClient client = HttpClients.createDefault();

        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();

        if(entity != null){
            String result = EntityUtils.toString(entity,"UTF-8");
            jsonObject = parseJSONP(result);
        }

        httpGet.releaseConnection();

        if(jsonObject != null){
            return jsonObject.getString("openid");
        }else {
            return null;
        }
    }

    //qq返回信息:{ "ret":0, "msg":"", "nickname":"YOUR_NICK_NAME", ... },為JSON格式,直接使用JSONObject對象解析
    public static JSONObject getUserInfo(String url) throws IOException {
        JSONObject jsonObject = null;
        CloseableHttpClient client = HttpClients.createDefault();

        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();


        if(entity != null){
            String result = EntityUtils.toString(entity,"UTF-8");
            jsonObject = JSONObject.parseObject(result);
        }

        httpGet.releaseConnection();

        return jsonObject;
    }
}

2.QQLoginController

下面是控制層完整代碼,如下:

package top.wangxingjun.separate.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import top.wangxingjun.separate.entity.User;
import top.wangxingjun.separate.result.Result;
import top.wangxingjun.separate.result.ResultFactory;
import top.wangxingjun.separate.service.UserService;
import top.wangxingjun.separate.util.QQHttpClient;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.UUID;


/** * @author wxj * @create 2019-09-27 20:32 * QQ第三方登陸接口 */
@Controller
@Log4j2
public class QQLoginController{
    @Value("${qq.oauth.http}")
    private String http;

    @Autowired
    private UserService userService;

    /** * 發起請求 * @param session * @return */
    @GetMapping("/api/qq/oauth")
    @ResponseBody
    public Result qq(HttpSession session){
        //QQ互聯中的回調地址
        String backUrl = http + "api/qq/callback";

        //用於第三方應用防止CSRF攻擊
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        session.setAttribute("state",uuid);

        //Step1:獲取Authorization Code
        String url = "https://graph.qq.com/oauth2.0/authorize?response_type=code"+
                "&client_id=" + QQHttpClient.APPID +
                "&redirect_uri=" + URLEncoder.encode(backUrl) +
                "&state=" + uuid;
        return ResultFactory.buildSuccessResult(url);
    }

    /** * QQ回調 注意 @GetMapping("/qq/callback")路徑 * 是要與QQ互聯填寫的回調路徑一致(我這里因為前端請求願意不用寫成 api/qq/callback) * @param request * @return */
    @GetMapping("/qq/callback")
    @ResponseBody
    public String qqcallback(HttpServletRequest request,HttpServletResponse response) throws Exception {
        response.setContentType("text/html; charset=utf-8");  // 響應編碼
        HttpSession session = request.getSession();
        //qq返回的信息:http://graph.qq.com/demo/index.jsp?code=9A5F************************06AF&state=test
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        String uuid = (String) session.getAttribute("state");

        if(uuid != null){
            if(!uuid.equals(state)){
                throw new Exception("QQ,state錯誤");
            }
        }
        //Step2:通過Authorization Code獲取Access Token
        String backUrl = http + "/qq/callback";
        String url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code"+
                "&client_id=" + QQHttpClient.APPID +
                "&client_secret=" + QQHttpClient.APPKEY +
                "&code=" + code +
                "&redirect_uri=" + backUrl;

        String access_token = QQHttpClient.getAccessToken(url);

        //Step3: 獲取回調后的 openid 值
        url = "https://graph.qq.com/oauth2.0/me?access_token=" + access_token;
        String openid = QQHttpClient.getOpenID(url);

        //Step4:獲取QQ用戶信息
        url = "https://graph.qq.com/user/get_user_info?access_token=" + access_token +
                "&oauth_consumer_key="+ QQHttpClient.APPID +
                "&openid=" + openid;

        JSONObject jsonObject = QQHttpClient.getUserInfo(url);
        //可以放到Redis和mysql中
        //session.setAttribute("openid",openid); //openid,用來唯一標識qq用戶
        //session.setAttribute("nickname",(String)jsonObject.get("nickname")); //QQ名
        //session.setAttribute("figureurl_qq_2",(String)jsonObject.get("figureurl_qq_2")); //大小為100*100像素的QQ頭像URL
        if(!userService.qqisExist(openid)){//用戶不存在
            User u=new User();
            u.setUsername(openid);
            u.setPassword("123456");
            u.setOpenid(openid);
            u.setName((String)jsonObject.get("nickname"));
            u.setTpath((String)jsonObject.get("figureurl_qq_2"));
            u.setEnabled(true);
            //注冊
            userService.qqregister(u);
            //redirect:../admin/dashboard
            return "<script>window.close();</script>";
        }
        User us=userService.findByOpenid(openid);
        UsernamePasswordToken token = new UsernamePasswordToken(us.getUsername(), "123456");
        SecurityUtils.getSubject().login(token);
        return "<script>window.opener.localStorage.setItem('username', '"+JSON.toJSONString(us)+"');window.close();</script>";
    }
}

我們可以看到,控制層中有兩處方法,第一個方法就是發起登錄的請求處理方法,第二個方法就是處理前端打開了QQ授權窗口之后,授權成功的回調請求處理方法(注意路徑要和你在QQ互聯上填寫回調路徑一致)。第二個方法里面便可以處理你的具體邏輯,比如是否是第一次登錄,按照自己業務需求來~ 而我這里的處理邏輯是:第一次登錄,那就進行注冊,然后通過返回一段js代碼,使前台的qq窗口關閉,這里我們重點要注意,看圖:
在這里插入圖片描述
對應的前端代碼,如下圖:
在這里插入圖片描述
通過監聽窗口是否關閉,來進行下一步邏輯處理。


三、郵件發送

上面已經將qq登錄相關的介紹完了,下面將郵件發送也補充上!(前期准備寫在上面了)
我這里的處理邏輯是:qq登錄時,如果從數據庫中通過openid查詢數據,不存在即表示需要注冊,然后調用注冊方法注冊。如果數據庫存在,即直接通過openid查詢對應信息,然后通過拼接js代碼的方式,將其對應信息存入前端vue中的localStorage里面。看下面圖:

在這里插入圖片描述
圖中的window.opener.localStorage.setItem(‘username’, ‘"+JSON.toJSONString(us)+"’);換成你自己的存放方法即可。重點是 window.close();能夠將前端qq窗口關閉。而window.opener,指向的是當前父級瀏覽器窗口~

呃呃呃呃呃~咋又扯到qq登錄相關的去了,算了,就算是解釋補充吧,畢竟是結合使用的。
好了,繼續下面的邏輯:當第一次登錄時,進行注冊,注冊成功之后發送qq郵件給管理員,這樣管理員就可以收到郵件。
下面看實現步驟:

1.引入依賴

<!--郵箱發送-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2.配置文件application.properties

# 郵件發送配置
# 因為是QQ郵箱,所以host需要使用smtp.qq.com。如果是其它郵箱,搜索下即可找到。
spring.mail.host=smtp.qq.com
# 這里便是寫你在qq郵箱設置的@foxmail.com
spring.mail.username=acechengui@foxmail.com  
# 這里便是寫你在qq郵箱設置POP3/SMTP服務生成的令牌
spring.mail.password=XXXXXXXXXX
# 編碼格式
spring.mail.default-encoding=UTF-8
#開啟加密驗證
spring.mail.properties.mail.smtp.ssl.enable=true

3.編碼

 @Autowired
 private JavaMailSender javaMailSender;

注入之后,我這里是將郵件發送,寫在業務層,相關代碼如下:

/** * 郵件發送 * @param username * @throws MessagingException * From需要和配置文件中的username一致,否則會報錯。 * To為郵件接收者; * Subject為郵件的標題; * Text為郵件的內容。 */
    public void mailSend(String username) throws MessagingException {
        //發送簡單郵件
        //SimpleMailMessage message = new SimpleMailMessage();
        //message.setFrom("acechengui@foxmail.com");
        //message.setTo("623169670@qq.com");
        //message.setSubject("用戶注冊通知");
        //message.setText("用戶"+username+"注冊成功,請及時進行賦權");
        //javaMailSender.send(message);

        //發送HTML郵件
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
        messageHelper.setSubject("用戶注冊通知");
        messageHelper.setFrom("acechengui@foxmail.com");
        messageHelper.setTo("623169670@qq.com");
        messageHelper.setText("<a href='javascript:void(0)'>用戶"+username+"注冊成功,請及時進行賦權</a>", true);
        javaMailSender.send(messageHelper.getMimeMessage());
    }

再到需要發送的地方調用此方法,這里有兩種發送郵件方式,一個簡單發送,另一種自定義格式的發送,當然還有攜帶文件的發送,那就的自行百度了實現起來基本一樣,比如我這里是注冊后發送郵件,看如下圖調用即可:
在這里插入圖片描述
到此,郵件發送使用介紹結束了,下面來看我的效果,看視頻:

vue springboot實現qq郵件發送

下面來看下注冊成功之后再進行qq登錄,看視頻:

vue springboot實現qq登錄

四、結束~

自己不自覺不夠努力,就不要怪別人不管你,不提醒你~ ------------------辰鬼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM