1. OAuth2解決什么問題?
OAuth2:是針對特定問題一種解決方案
可以解決兩個問題:
a. 開放系統間授權
b. 分布式訪問問題
解決方案:
a. 方式一:用戶名密碼復制
b. 通用開發者key
c. 辦法令牌
2. 微信掃描登錄
點擊進行注冊開發者認證
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發送請求,得到返回結果 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 ); //發送請求 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); } /** * 發送一個 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<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")) { // 執行 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) { // 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 前端
點擊微信登錄 發送請求
<div class="more-sign"> <h6>社交帳號登錄</h6> <ul> <li><a id="weixin" class="weixin" target="_blank" href="http://127.0.0.1:8160/api/ucenter/wx/login" 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整合微信登錄內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/qq_39759664/article/details/120980738