SpringBoot整合微信登錄功能的實(shí)現(xiàn)方案
1. OAuth2解決什么問(wèn)題?
OAuth2:是針對(duì)特定問(wèn)題一種解決方案
可以解決兩個(gè)問(wèn)題:
a. 開(kāi)放系統(tǒng)間授權(quán)
b. 分布式訪問(wèn)問(wèn)題
解決方案:
a. 方式一:用戶名密碼復(fù)制
b. 通用開(kāi)發(fā)者key
c. 辦法令牌
2. 微信掃描登錄
點(diǎn)擊進(jìn)行注冊(cè)開(kāi)發(fā)者認(rèn)證
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 添加配置
下面的配置是你申請(qǐng)的有關(guān)的,重定向鏈接是登陸成功需要跳轉(zhuǎn)的請(qǐng)求
# 微信開(kāi)放平臺(tái) appid wx.open.app_id=wxed94c01bb89b47 # 微信開(kāi)放平臺(tái) appsecret wx.open.app_secret=a7482517235173ddb43788de60b90e # 微信開(kāi)放平臺(tái) 重定向url wx.open.redirect_url=http://localhost:8160/api/ucenter/wx/callback
2.3 登錄請(qǐng)求
//1 生成微信掃描二維碼 @GetMapping("login") public String getWxCode() { System.out.println("調(diào)用了兄弟。。。。。。。。。。。。。。。。。。。。。。。。。。。。。"); //固定地址,后面拼接參數(shù) // String url = "https://open.weixin.qq.com/" + // "connect/qrconnect?appid="+ ConstantWxUtils.WX_OPEN_APP_ID+"&response_type=code"; // 微信開(kāi)放平臺(tái)授權(quán)baseUrl %s相當(dāng)于?代表占位符 String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" + "?appid=%s" + "&redirect_uri=%s" + "&response_type=code" + "&scope=snsapi_login" + "&state=%s" + "#wechat_redirect"; //對(duì)redirect_url進(jìn)行URLEncoder編碼 String redirectUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL; try { redirectUrl = URLEncoder.encode(redirectUrl, "utf-8"); }catch(Exception e) { } //設(shè)置%s里面值 String url = String.format( baseUrl, ConstantWxUtils.WX_OPEN_APP_ID, redirectUrl, "atguigu" ); //重定向到請(qǐng)求微信地址里面 return "redirect:"+url; }
請(qǐng)求成功后,掃描二維碼點(diǎn)擊缺點(diǎn)登錄
會(huì)自動(dòng)調(diào)用callback
//2 獲取掃描人信息,添加數(shù)據(jù) @GetMapping("callback") public String callback(String code, String state) { try { //1 獲取code值,臨時(shí)票據(jù),類似于驗(yàn)證碼 //2 拿著code請(qǐng)求 微信固定的地址,得到兩個(gè)值 accsess_token 和 openid String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" + "?appid=%s" + "&secret=%s" + "&code=%s" + "&grant_type=authorization_code"; //拼接三個(gè)參數(shù) :id 秘鑰 和 code值 String accessTokenUrl = String.format( baseAccessTokenUrl, ConstantWxUtils.WX_OPEN_APP_ID, ConstantWxUtils.WX_OPEN_APP_SECRET, code ); //請(qǐng)求這個(gè)拼接好的地址,得到返回兩個(gè)值 accsess_token 和 openid //使用httpclient發(fā)送請(qǐng)求,得到返回結(jié)果 String accessTokenInfo = HttpClientUtils.get(accessTokenUrl); //從accessTokenInfo字符串獲取出來(lái)兩個(gè)值 accsess_token 和 openid //把a(bǔ)ccessTokenInfo字符串轉(zhuǎn)換map集合,根據(jù)map里面key獲取對(duì)應(yīng)值 //使用json轉(zhuǎn)換工具 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"); //把掃描人信息添加數(shù)據(jù)庫(kù)里面 //判斷數(shù)據(jù)表里面是否存在相同微信信息,根據(jù)openid判斷 UcenterMember member = memberService.getOpenIdMember(openid); if(member == null) {//memeber是空,表沒(méi)有相同微信數(shù)據(jù),進(jìn)行添加 //3 拿著得到accsess_token 和 openid,再去請(qǐng)求微信提供固定的地址,獲取到掃描人信息 //訪問(wèn)微信的資源服務(wù)器,獲取用戶信息 String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" + "?access_token=%s" + "&openid=%s"; //拼接兩個(gè)參數(shù) String userInfoUrl = String.format( baseUserInfoUrl, access_token, openid ); //發(fā)送請(qǐng)求 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根據(jù)member對(duì)象生成token字符串 String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname()); //最后:返回首頁(yè)面,通過(guò)路徑傳遞token字符串 return "redirect:http://localhost:3000?token="+jwtToken; }catch(Exception e) { throw new GuliException(20001,"登錄失敗"); } }
查找用戶信息根據(jù)token
//根據(jù)token獲取用戶的信息 @GetMapping("getmemberInfo") public R getmemberInfo(HttpServletRequest request){ //調(diào)用jwt工具類,根據(jù)request對(duì)象獲取頭部信息 //獲的用戶的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ā)送一個(gè) Post 請(qǐng)求, 使用指定的字符集編碼. * * @param url * @param body RequestBody * @param mimeType 例如 application/xml "application/x-www-form-urlencoded" a=1&b=2&c=3 * @param charset 編碼 * @param connTimeout 建立鏈接超時(shí)時(shí)間,毫秒. * @param readTimeout 響應(yīng)超時(shí)時(shí)間,毫秒. * @return ResponseBody, 使用指定的字符集編碼. * @throws ConnectTimeoutException 建立鏈接超時(shí)異常 * @throws SocketTimeoutException 響應(yīng)超時(shí) * @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); } // 設(shè)置參數(shù) 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 請(qǐng)求. client = createSSLInsecureClient(); res = client.execute(post); } else { // 執(zhí)行 Http 請(qǐng)求. 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()); } } // 設(shè)置參數(shù) 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 請(qǐng)求. client = createSSLInsecureClient(); res = client.execute(post); } else { // 執(zhí)行 Http 請(qǐng)求. 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ā)送一個(gè) GET 請(qǐng)求 * * @param url * @param charset * @param connTimeout 建立鏈接超時(shí)時(shí)間,毫秒. * @param readTimeout 響應(yīng)超時(shí)時(shí)間,毫秒. * @return * @throws ConnectTimeoutException 建立鏈接超時(shí) * @throws SocketTimeoutException 響應(yīng)超時(shí) * @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 { // 設(shè)置參數(shù) 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 請(qǐng)求. client = createSSLInsecureClient(); res = client.execute(get); } else { // 執(zhí)行 Http 請(qǐng)求. 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 前端
點(diǎn)擊微信登錄 發(fā)送請(qǐng)求
<div class="more-sign"> <h6>社交帳號(hào)登錄</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>
到二維碼的界面
掃描后 點(diǎn)擊登錄
將后端傳遞的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')) //調(diào)用接口,根據(jù)token值獲取用戶信息 loginApi.getLoginUserInfo() .then(response => { this.loginInfo = response.data.data.userInfo cookie.set('guli_ucenter',this.loginInfo,{domain: 'localhost'}) }) },
到此這篇關(guān)于微信登錄與SpringBoot整合的文章就介紹到這了,更多相關(guān)SpringBoot整合微信登錄內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
如何通過(guò)Java實(shí)現(xiàn)加密、解密Word文檔
這篇文章主要介紹了如何通過(guò)Java實(shí)現(xiàn)加密、解密Word文檔,對(duì)一些重要文檔,常需要對(duì)文件進(jìn)行加密,查看文件時(shí),需要正確輸入密碼才能打開(kāi)文件。下面介紹了一種比較簡(jiǎn)單的方法給Word文件加密以及如何給已加密的Word文件解除密碼保護(hù),需要的朋友可以參考下2019-07-07SSH結(jié)合jquery實(shí)現(xiàn)三級(jí)聯(lián)動(dòng)效果
這篇文章主要為大家詳細(xì)介紹了SSH結(jié)合jquery實(shí)現(xiàn)三級(jí)聯(lián)動(dòng)效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-01-01java實(shí)現(xiàn)輸出字符串中第一個(gè)出現(xiàn)不重復(fù)的字符詳解
這篇文章主要介紹了java實(shí)現(xiàn)輸出字符串中第一個(gè)出現(xiàn)不重復(fù)的字符詳解的相關(guān)資料,需要的朋友可以參考下2017-04-04Spring Security 密碼驗(yàn)證動(dòng)態(tài)加鹽的驗(yàn)證處理方法
小編最近在改造項(xiàng)目,需要將gateway整合security在一起進(jìn)行認(rèn)證和鑒權(quán),今天小編給大家分享Spring Security 密碼驗(yàn)證動(dòng)態(tài)加鹽的驗(yàn)證處理方法,感興趣的朋友一起看看吧2021-06-06關(guān)于mybatis-plus邏輯刪除無(wú)效的問(wèn)題
這篇文章主要介紹了mybatis-plus邏輯刪除無(wú)效,文中給大家提到了配置過(guò)程及全部代碼,代碼簡(jiǎn)單易懂,需要的朋友可以參考下2021-09-09springboot打包部署到linux服務(wù)器的方法
這篇文章主要介紹了springboot打包部署到linux服務(wù)器的方法,通過(guò)實(shí)例代碼相結(jié)合的形式給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-06-06