QQ第三方授權登錄+阿里雲短信服務

一、簡介

目前我們使用的web系統在登陸功能開發時,不僅僅只是單純的使用表單填寫用戶註冊信息來進行註冊,參考我們現在使用的其他軟件存在以下登錄情況。

  1. 使用QQ/微信等第三方平臺進行授權登錄
  2. 使用短信驗證碼進行登錄

常見的就是着兩種登錄方式,他們使用的頻率比單純的表單填寫信息更加的美觀。

注意:我們這篇文章只是讓我們瞭解第三方平臺賬號授權和手機驗證碼,在此不過多關注和區分登錄和註冊的邏輯。

二、QQ第三方授權登錄

1.獲得QQ的權限

進入QQ互聯—>點擊頭像填寫個人信息—>應用管理

(審覈需要一定的時間)可以參考QQ互聯文檔資料

在這裏插入圖片描述

2.代碼的編寫

2.1添加依賴

我們再springboot實現該功能

	<!-- 以下是 qq 登陸需要的相關依賴工具 commons-io, commons-lang3,httpclient,fastjson-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.38</version>
        </dependency>

2.2配置文件信息

填寫QQ互聯的Appid,key,登錄後回調地址(必須和QQ互聯填寫的一致,QQLogin 對應代碼裏的接口)

constants.qqAppId=101513767
constants.qqAppSecret=b1d978cefcf405388893d8e686d307b0
constants.qqRedirectUrl=http://127.0.0.1:8080/QQLogin

2.3讀取配置信息類

@Component
public class Constants {

	@Value("${constants.qqAppId}")
	private String qqAppId;

	@Value("${constants.qqAppSecret}")
	private String qqAppSecret;

	@Value("${constants.qqRedirectUrl}")
	private String qqRedirectUrl;

	@Value("${constants.weCatAppId}")
	private String weCatAppId;

	@Value("${constants.weCatAppSecret}")
	private String weCatAppSecret;

	@Value("${constants.weCatRedirectUrl}")
	private String weCatRedirectUrl;

	//自行生成set get方法
}

2.4QQ數據實體類

QQ將把返回的信息封裝到這裏

public class QQUserInfo {

	private Integer ret;
	private String msg;
	private Integer is_lost;
	private String nickname;
	private String gender;
	private String province;
	private String city;
	private String year;
	private String constellation;
	private String figureurl;
	private String figureurl_1;
	private String figureurl_2;
	private String figureurl_qq;
	private String figureurl_qq_1;
	private String figureurl_qq_2;
	private String is_yellow_vip;
	private String vip;
	private String yellow_vip_level;
	private String level;
	private String is_yellow_year_vip;
	
   //自行生成 set get
}

2.5http工具類 HttpClientUtils

public class HttpClientUtils {

    public static final int connTimeout = 10000;
    public static final int readTimeout = 10000;
    public static final String charset = "UTF-8";
    private static HttpClient client = null;

    static {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(128);
        cm.setDefaultMaxPerRoute(128);
        client = HttpClients.custom().setConnectionManager(cm).build();
    }

    public static String postParameters(String url, String parameterStr)
            throws ConnectTimeoutException, SocketTimeoutException, Exception {
        return post(url, parameterStr, "application/x-www-form-urlencoded", charset, connTimeout, readTimeout);
    }

    public static String postParameters(String url, String parameterStr, String charset, Integer connTimeout,
                                        Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception {
        return post(url, parameterStr, "application/x-www-form-urlencoded", charset, connTimeout, readTimeout);
    }

    public static String postParameters(String url, Map<String, String> params)
            throws ConnectTimeoutException, SocketTimeoutException, Exception {
        return postForm(url, params, null, connTimeout, readTimeout);
    }

    public static String postParameters(String url, Map<String, String> params, Integer connTimeout,
                                        Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception {
        return postForm(url, params, null, connTimeout, readTimeout);
    }

    public static String get(String url) throws Exception {
        return get(url, charset, null, null);
    }

    public static String get(String url, String charset) throws Exception {
        return get(url, charset, connTimeout, readTimeout);
    }

    /**
     * 發送一個 Post 請求, 使用指定的字符集編碼.
     *
     * @param url
     * @param body        RequestBody
     * @param mimeType    例如 application/xml "application/x-www-form-urlencoded"
     *                    a=1&b=2&c=3
     * @param charset     編碼
     * @param connTimeout 建立鏈接超時時間,毫秒.
     * @param readTimeout 響應超時時間,毫秒.
     * @return ResponseBody, 使用指定的字符集編碼.
     * @throws ConnectTimeoutException 建立鏈接超時異常
     * @throws SocketTimeoutException  響應超時
     * @throws Exception
     */
    public static String post(String url, String body, String mimeType, String charset, Integer connTimeout,
                              Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception {
        HttpClient client = null;
        HttpPost post = new HttpPost(url);
        String result = "";
        try {
            if (StringUtils.isNotBlank(body)) {
                HttpEntity entity = new StringEntity(body, ContentType.create(mimeType, charset));
                post.setEntity(entity);
            }
            // 設置參數
            Builder customReqConf = RequestConfig.custom();
            if (connTimeout != null) {
                customReqConf.setConnectTimeout(connTimeout);
            }
            if (readTimeout != null) {
                customReqConf.setSocketTimeout(readTimeout);
            }
            post.setConfig(customReqConf.build());

            HttpResponse res;
            if (url.startsWith("https")) {
                // 執行 Https 請求.
                client = createSSLInsecureClient();
                res = client.execute(post);
            } else {
                // 執行 Http 請求.
                client = HttpClientUtils.client;
                res = client.execute(post);
            }
            result = IOUtils.toString(res.getEntity().getContent(), charset);
        } finally {
            post.releaseConnection();
            if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) {
                ((CloseableHttpClient) client).close();
            }
        }
        return result;
    }

    /**
     * 提交form表單
     *
     * @param url
     * @param params
     * @param connTimeout
     * @param readTimeout
     * @return
     * @throws ConnectTimeoutException
     * @throws SocketTimeoutException
     * @throws Exception
     */
    public static String postForm(String url, Map<String, String> params, Map<String, String> headers,
                                  Integer connTimeout, Integer readTimeout)
            throws ConnectTimeoutException, SocketTimeoutException, Exception {

        HttpClient client = null;
        HttpPost post = new HttpPost(url);
        try {
            if (params != null && !params.isEmpty()) {
                List<NameValuePair> formParams = new ArrayList<org.apache.http.NameValuePair>();
                Set<Map.Entry<String, String>> entrySet = params.entrySet();
                for (Map.Entry<String, String> entry : entrySet) {
                    formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);
                post.setEntity(entity);
            }

            if (headers != null && !headers.isEmpty()) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    post.addHeader(entry.getKey(), entry.getValue());
                }
            }
            // 設置參數
            Builder customReqConf = RequestConfig.custom();
            if (connTimeout != null) {
                customReqConf.setConnectTimeout(connTimeout);
            }
            if (readTimeout != null) {
                customReqConf.setSocketTimeout(readTimeout);
            }
            post.setConfig(customReqConf.build());
            HttpResponse res = null;
            if (url.startsWith("https")) {
                // 執行 Https 請求.
                client = createSSLInsecureClient();
                res = client.execute(post);
            } else {
                // 執行 Http 請求.
                client = HttpClientUtils.client;
                res = client.execute(post);
            }
            return IOUtils.toString(res.getEntity().getContent(), "UTF-8");
        } finally {
            post.releaseConnection();
            if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) {
                ((CloseableHttpClient) client).close();
            }
        }
    }

    /**
     * 發送一個 GET 請求
     *
     * @param url
     * @param charset
     * @param connTimeout 建立鏈接超時時間,毫秒.
     * @param readTimeout 響應超時時間,毫秒.
     * @return
     * @throws ConnectTimeoutException 建立鏈接超時
     * @throws SocketTimeoutException  響應超時
     * @throws Exception
     */
    public static String get(String url, String charset, Integer connTimeout, Integer readTimeout)
            throws ConnectTimeoutException, SocketTimeoutException, Exception {

        HttpClient client = null;
        HttpGet get = new HttpGet(url);
        String result = "";
        try {
            // 設置參數
            Builder customReqConf = RequestConfig.custom();
            if (connTimeout != null) {
                customReqConf.setConnectTimeout(connTimeout);
            }
            if (readTimeout != null) {
                customReqConf.setSocketTimeout(readTimeout);
            }
            get.setConfig(customReqConf.build());

            HttpResponse res = null;

            if (url.startsWith("https")) {
                // 執行 Https 請求.
                client = createSSLInsecureClient();
                res = client.execute(get);
            } else {
                // 執行 Http 請求.
                client = HttpClientUtils.client;
                res = client.execute(get);
            }

            result = IOUtils.toString(res.getEntity().getContent(), charset);
        } finally {
            get.releaseConnection();
            if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) {
                ((CloseableHttpClient) client).close();
            }
        }
        return result;
    }

    /**
     * 從 response 裏獲取 charset
     *
     * @param ressponse
     * @return
     */
    @SuppressWarnings("unused")
    private static String getCharsetFromResponse(HttpResponse ressponse) {
        // Content-Type:text/html; charset=GBK
        if (ressponse.getEntity() != null && ressponse.getEntity().getContentType() != null
                && ressponse.getEntity().getContentType().getValue() != null) {
            String contentType = ressponse.getEntity().getContentType().getValue();
            if (contentType.contains("charset=")) {
                return contentType.substring(contentType.indexOf("charset=") + 8);
            }
        }
        return null;
    }

    /**
     * 創建 SSL連接
     *
     * @return
     * @throws GeneralSecurityException
     */
    private static CloseableHttpClient createSSLInsecureClient() throws GeneralSecurityException {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();

            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {

                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }

                @Override
                public void verify(String host, SSLSocket ssl) throws IOException {
                }

                @Override
                public void verify(String host, X509Certificate cert) throws SSLException {
                }

                @Override
                public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
                }

            });

            return HttpClients.custom().setSSLSocketFactory(sslsf).build();

        } catch (GeneralSecurityException e) {
            throw e;
        }
    }

    public static void main(String[] args) {
        try {
            String str = post("https://localhost:443/ssl/test.shtml", "name=12&page=34",
                    "application/x-www-form-urlencoded", "UTF-8", 10000, 10000);
            // String str=
            // get("https://localhost:443/ssl/test.shtml?name=12&page=34","GBK");
            /*
             * Map<String,String> map = new HashMap<String,String>(); map.put("name",
             * "111"); map.put("page", "222"); String str=
             * postForm("https://localhost:443/ssl/test.shtml",map,null, 10000, 10000);
             */
            System.out.println(str);
        } catch (ConnectTimeoutException e) {
            e.printStackTrace();
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2.6url轉碼工具類 URLEncodeUtil

不管是以何種方式傳遞url時,如果要傳遞的url中包含特殊字符,如想要傳遞一個+,但是這個+會被url會被編碼成空格,想要傳遞&,被url處理成分隔符。所以都會做一下url轉碼的工作。

public class URLEncodeUtil {

    private final static String ENCODE = "UTF-8";
    /**
     * URL 解碼
     */
    public static String getURLDecoderString(String str) {
        String result = "";
        if (null == str) {
            return "";
        }
        try {
            result = java.net.URLDecoder.decode(str, ENCODE);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }
    /**
     * URL 轉碼
     */
    public static String getURLEncoderString(String str) {
        String result = "";
        if (null == str) {
            return "";
        }
        try {
            result = java.net.URLEncoder.encode(str, ENCODE);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }
}

2.7全段頁面

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="/getQQCode">獲取qq登錄連接</a>
<div th:text="${url}"></div>
<a th:href="${url}">開始登錄</a>
<br>
<a href="/wxLogin">跳到微信登錄頁</a>
</body>
</html>

2.8效果

授權後返回的信息

在這裏插入圖片描述

二、短信授權登錄

短信登陸可以參考:微信開放平臺官方文檔

三、短信驗證登錄

我們使用阿里雲短信服務來完成發送驗證碼

1.阿里雲短息服務

進去阿里雲,搜索短信服務,完成學習應該就瞭解的差不多了

1.添加簽名和模板

  • 選擇左側的國內消
  • 簽名管理中選擇添加簽名(簽名就是發送短信時的程序名或公司名)需審覈
  • 模板管理添加模板(也就是發送短信的內容)需審覈

2.獲取自己的阿里雲私匙

  • 左側點擊概覽
  • 選擇AccessKey(獲得私匙)

2.代碼實現

可以參考OpenAPI Explorer

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章