最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot整合微信登錄功能的實現方案

 更新時間:2021年10月28日 10:38:46   作者:小玩偶啊  
今天通過本文給大家分享微信登錄與SpringBoot整合過程,微信掃描登錄實現代碼知道掃描后點擊登錄的全部過程,本文給大家介紹的非常詳細,需要的朋友可以參考下

1. OAuth2解決什么問題?

OAuth2:是針對特定問題一種解決方案
可以解決兩個問題:
a. 開放系統(tǒng)間授權
b. 分布式訪問問題

解決方案:
a. 方式一:用戶名密碼復制

在這里插入圖片描述

b. 通用開發(fā)者key

在這里插入圖片描述

c. 辦法令牌

在這里插入圖片描述

在這里插入圖片描述

2. 微信掃描登錄

點擊進行注冊開發(fā)者認證
JWT配置

2.1 添加必要的依賴

  <!--httpclient-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
        <!--commons-io-->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
        </dependency>
        <!--gson-->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
        </dependency>
    </dependencies>

2.2 application.properties 添加配置

下面的配置是你申請的有關的,重定向鏈接是登陸成功需要跳轉的請求

# 微信開放平臺 appid
wx.open.app_id=wxed94c01bb89b47
# 微信開放平臺 appsecret
wx.open.app_secret=a7482517235173ddb43788de60b90e
# 微信開放平臺 重定向url
wx.open.redirect_url=http://localhost:8160/api/ucenter/wx/callback

2.3 登錄請求

//1 生成微信掃描二維碼
    @GetMapping("login")
    public String getWxCode() {
        System.out.println("調用了兄弟。。。。。。。。。。。。。。。。。。。。。。。。。。。。。");
        //固定地址,后面拼接參數
//        String url = "https://open.weixin.qq.com/" +
//                "connect/qrconnect?appid="+ ConstantWxUtils.WX_OPEN_APP_ID+"&response_type=code";

        // 微信開放平臺授權baseUrl  %s相當于?代表占位符
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        //對redirect_url進行URLEncoder編碼
        String redirectUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "utf-8");
        }catch(Exception e) {
        }

        //設置%s里面值
        String url = String.format(
                baseUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                redirectUrl,
                "atguigu"
        );

        //重定向到請求微信地址里面
        return "redirect:"+url;
    }

請求成功后,掃描二維碼點擊缺點登錄
會自動調用callback

 //2 獲取掃描人信息,添加數據
    @GetMapping("callback")
    public String callback(String code, String state) {
        try {
            //1 獲取code值,臨時票據,類似于驗證碼
            //2 拿著code請求 微信固定的地址,得到兩個值 accsess_token 和 openid
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";
            //拼接三個參數 :id  秘鑰 和 code值
            String accessTokenUrl = String.format(
                    baseAccessTokenUrl,
                    ConstantWxUtils.WX_OPEN_APP_ID,
                    ConstantWxUtils.WX_OPEN_APP_SECRET,
                    code
            );
            //請求這個拼接好的地址,得到返回兩個值 accsess_token 和 openid
            //使用httpclient發(fā)送請求,得到返回結果
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);

            //從accessTokenInfo字符串獲取出來兩個值 accsess_token 和 openid
            //把accessTokenInfo字符串轉換map集合,根據map里面key獲取對應值
            //使用json轉換工具 Gson
            Gson gson = new Gson();
            HashMap mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);
            String access_token = (String)mapAccessToken.get("access_token");
            String openid = (String)mapAccessToken.get("openid");

            //把掃描人信息添加數據庫里面
            //判斷數據表里面是否存在相同微信信息,根據openid判斷
            UcenterMember member = memberService.getOpenIdMember(openid);
            if(member == null) {//memeber是空,表沒有相同微信數據,進行添加

                //3 拿著得到accsess_token 和 openid,再去請求微信提供固定的地址,獲取到掃描人信息
                //訪問微信的資源服務器,獲取用戶信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                //拼接兩個參數
                String userInfoUrl = String.format(
                        baseUserInfoUrl,
                        access_token,
                        openid
                );
                //發(fā)送請求
                String userInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println("userInfo::::"+userInfo);
                //獲取返回userinfo字符串掃描人信息
                HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);
                String nickname = (String)userInfoMap.get("nickname");//昵稱
                String headimgurl = (String)userInfoMap.get("headimgurl");//頭像

                member = new UcenterMember();
                member.setOpenid(openid);
                member.setNickname(nickname);
                member.setAvatar(headimgurl);
                memberService.save(member);
            }

            //使用jwt根據member對象生成token字符串
            String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
            //最后:返回首頁面,通過路徑傳遞token字符串
            return "redirect:http://localhost:3000?token="+jwtToken;
        }catch(Exception e) {
            throw new GuliException(20001,"登錄失敗");
        }
    }

查找用戶信息根據token

   //根據token獲取用戶的信息
    @GetMapping("getmemberInfo")
    public R getmemberInfo(HttpServletRequest request){
        //調用jwt工具類,根據request對象獲取頭部信息
        //獲的用戶的id
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        UcenterMember ucenterMember = memberService.getById(memberId);
        return R.ok().data("userInfo",ucenterMember);
    }

ConstantWxUtils 獲取配置文件的值

@Component
public class ConstantWxUtils implements InitializingBean {

    @Value("${wx.open.app_id}")
    private String appId;

    @Value("${wx.open.app_secret}")
    private String appSecret;

    @Value("${wx.open.redirect_url}")
    private String redirectUrl;

    public static String WX_OPEN_APP_ID;
    public static String WX_OPEN_APP_SECRET;
    public static String WX_OPEN_REDIRECT_URL;

    @Override
    public void afterPropertiesSet() throws Exception {
        WX_OPEN_APP_ID = appId;
        WX_OPEN_APP_SECRET = appSecret;
        WX_OPEN_REDIRECT_URL = redirectUrl;
    }
}

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);
	}

	/**
	 * 發(fā)送一個 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")) {
				// 執(zhí)行 Https 請求.
				client = createSSLInsecureClient();
				res = client.execute(post);
			} else {
				// 執(zhí)行 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<NameValuePair>();
				Set<Entry<String, String>> entrySet = params.entrySet();
				for (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 (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")) {
				// 執(zhí)行 Https 請求.
				client = createSSLInsecureClient();
				res = client.execute(post);
			} else {
				// 執(zhí)行 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();
			}
		}
	}




	/**
	 * 發(fā)送一個 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")) {
				// 執(zhí)行 Https 請求.
				client = createSSLInsecureClient();
				res = client.execute(get);
			} else {
				// 執(zhí)行 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;
	}



	/**
	 * 創(chuàng)建 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) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SocketTimeoutException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

2.4 前端

點擊微信登錄 發(fā)送請求

      <div class="more-sign">
        <h6>社交帳號登錄</h6>
        <ul>
          <li><a id="weixin" class="weixin" target="_blank"  rel="external nofollow" ><i class="iconfont icon-weixin"/></a></li>
          <li><a id="qq" class="qq" target="_blank" href="#" rel="external nofollow" ><i class="iconfont icon-qq"/></a></li>
        </ul>
      </div>

到二維碼的界面

在這里插入圖片描述

掃描后 點擊登錄
將后端傳遞的token值中的用戶信息交給前端

created() {
    //獲取路徑里面token值?后面的值
    this.token = this.$route.query.token
    console.log(this.token)
    if(this.token) {//判斷路徑是否有token值
       this.wxLogin()
    }
  },
  //微信登錄顯示的方法
    wxLogin() {
      //console.log('************'+this.token)
      //把token值放到cookie里面
      cookie.set('guli_token',this.token,{domain: 'localhost'})
      cookie.set('guli_ucenter','',{domain: 'localhost'})
     //console.log('====='+cookie.get('guli_token'))
      //調用接口,根據token值獲取用戶信息
      loginApi.getLoginUserInfo()
        .then(response => {
           this.loginInfo = response.data.data.userInfo
           cookie.set('guli_ucenter',this.loginInfo,{domain: 'localhost'})
        })
    },

到此這篇關于微信登錄與SpringBoot整合的文章就介紹到這了,更多相關SpringBoot整合微信登錄內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • 深入理解Hibernate中的懶加載異常及解決方法

    深入理解Hibernate中的懶加載異常及解決方法

    這篇文章主要為大家介紹了深入理解Hibernate中的懶加載異常及解決方法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪<BR>
    2023-10-10
  • knife4j?整合?springboot的過程詳解

    knife4j?整合?springboot的過程詳解

    這篇文章主要介紹了knife4j整合springboot的過程,本次整合springboot版本為2.3.12,本文通過圖文實例相結合給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-09-09
  • springboot 單文件上傳的實現步驟

    springboot 單文件上傳的實現步驟

    這篇文章主要介紹了springboot實現單文件上傳的方法,幫助大家更好的理解和使用springboot框架,感興趣的朋友可以了解下
    2021-02-02
  • Java對稱加密工作模式原理詳解

    Java對稱加密工作模式原理詳解

    這篇文章主要介紹了Java對稱加密工作模式原理詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-02-02
  • Spring事務傳播行為問題解決

    Spring事務傳播行為問題解決

    這篇文章主要介紹了Spring事務傳播行為問題解決,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-01-01
  • 詳解SpringBoot定時任務功能

    詳解SpringBoot定時任務功能

    這篇文章主要介紹了SpringBoot定時任務功能詳細解析,這次的功能開發(fā)過程中也算是對其內涵的進一步了解,以后遇到定時任務的處理也更清晰,更有效率了,對SpringBoot定時任務相關知識感興趣的朋友一起看看吧
    2022-05-05
  • SpringBoot實現ImportBeanDefinitionRegistrar動態(tài)注入

    SpringBoot實現ImportBeanDefinitionRegistrar動態(tài)注入

    在閱讀Spring Boot源碼時,看到Spring Boot中大量使用ImportBeanDefinitionRegistrar來實現Bean的動態(tài)注入,它是Spring中一個強大的擴展接口,本文就來詳細的介紹一下如何使用,感興趣的可以了解一下
    2024-02-02
  • java實現小貓釣魚游戲

    java實現小貓釣魚游戲

    這篇文章主要為大家詳細介紹了java實現小貓釣魚游戲,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-01-01
  • java數組實現循環(huán)隊列示例介紹

    java數組實現循環(huán)隊列示例介紹

    大家好,本篇文章主要講的是java數組實現循環(huán)隊列示例介紹,感興趣的同學趕快來看一看吧,對你有幫助的話記得收藏一下,方便下次瀏覽
    2022-01-01
  • Maven繼承父工程時的relativePath標簽解析用法小結

    Maven繼承父工程時的relativePath標簽解析用法小結

    relativePath 的作用是為了找到父級工程的pom.xml,本文主要介紹了Maven繼承父工程時的relativePath標簽解析用法小結,具有一定的參考價值,感興趣的可以了解一下
    2024-03-03

最新評論

玛纳斯县| 盐边县| 扎囊县| 山阳县| 基隆市| 泾源县| 修武县| 万山特区| 江油市| 常宁市| 乐安县| 郎溪县| 洪江市| 慈利县| 霍山县| 合江县| 罗山县| 金平| 永善县| 武鸣县| 阜康市| 乡城县| 宣化县| 沁水县| 宁南县| 建瓯市| 温州市| 尉犁县| 江永县| 平潭县| 三河市| 威远县| 宁安市| 盈江县| 安达市| 红安县| 杂多县| 文安县| 宝清县| 安吉县| 奉新县|