這篇文章將為大家詳細(xì)講解有關(guān)Springboot怎么實(shí)現(xiàn)網(wǎng)站第三方登錄,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
在徐水等地區(qū),都構(gòu)建了全面的區(qū)域性戰(zhàn)略布局,加強(qiáng)發(fā)展的系統(tǒng)性、市場(chǎng)前瞻性、產(chǎn)品創(chuàng)新能力,以專注、極致的服務(wù)理念,為客戶提供成都網(wǎng)站制作、網(wǎng)站設(shè)計(jì) 網(wǎng)站設(shè)計(jì)制作按需求定制設(shè)計(jì),公司網(wǎng)站建設(shè),企業(yè)網(wǎng)站建設(shè),高端網(wǎng)站設(shè)計(jì),營銷型網(wǎng)站建設(shè),成都外貿(mào)網(wǎng)站建設(shè),徐水網(wǎng)站建設(shè)費(fèi)用合理。
微信開放平臺(tái)接入,官網(wǎng):https://open.weixin.qq.com,在官網(wǎng)注冊(cè)并添加應(yīng)用后即可獲得APP_ID和APP_SECRET。
步驟一:創(chuàng)建一個(gè)繼承AuthService的接口,WeChatAuthService,如下
public interface WeChatAuthService extends AuthService { public JSONObject getUserInfo(String accessToken, String openId); }
步驟二:WeChatService的具體實(shí)現(xiàn)如下
@Service public class WeChatAuthServiceImpl extends DefaultAuthServiceImpl implements WeChatAuthService { private Logger logger = LoggerFactory.getLogger(WeChatAuthServiceImpl.class); //請(qǐng)求此地址即跳轉(zhuǎn)到二維碼登錄界面 private static final String AUTHORIZATION_URL = "https://open.weixin.qq.com/connect/qrconnect?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect"; // 獲取用戶 openid 和access——toke 的 URL private static final String ACCESSTOKE_OPENID_URL = "https://api.weixin.qq.com/sns/oauth3/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code"; private static final String REFRESH_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth3/refresh_token?appid=%s&grant_type=refresh_token&refresh_token=%s"; private static final String USER_INFO_URL = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN"; private static final String APP_ID="xxxxxx"; private static final String APP_SECRET="xxxxxx"; private static final String SCOPE = "snsapi_login"; private String callbackUrl = "https://www.xxx.cn/auth/wechat"; //回調(diào)域名 @Override public String getAuthorizationUrl() throws UnsupportedEncodingException { callbackUrl = URLEncoder.encode(callbackUrl,"utf-8"); String url = String.format(AUTHORIZATION_URL,APP_ID,callbackUrl,SCOPE,System.currentTimeMillis()); return url; } @Override public String getAccessToken(String code) { String url = String.format(ACCESSTOKE_OPENID_URL,APP_ID,APP_SECRET,code); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url); URI uri = builder.build().encode().toUri(); String resp = getRestTemplate().getForObject(uri, String.class); logger.error("getAccessToken resp = "+resp); if(resp.contains("openid")){ JSONObject jsonObject = JSONObject.parseObject(resp); String access_token = jsonObject.getString("access_token"); String openId = jsonObject.getString("openid");; JSONObject res = new JSONObject(); res.put("access_token",access_token); res.put("openId",openId); res.put("refresh_token",jsonObject.getString("refresh_token")); return res.toJSONString(); }else{ throw new ServiceException("獲取token失敗,msg = "+resp); } } //微信接口中,token和openId是一起返回,故此方法不需實(shí)現(xiàn) @Override public String getOpenId(String accessToken) { return null; } @Override public JSONObject getUserInfo(String accessToken, String openId){ String url = String.format(USER_INFO_URL, accessToken, openId); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url); URI uri = builder.build().encode().toUri(); String resp = getRestTemplate().getForObject(uri, String.class); logger.error("getUserInfo resp = "+resp); if(resp.contains("errcode")){ throw new ServiceException("獲取用戶信息錯(cuò)誤,msg = "+resp); }else{ JSONObject data =JSONObject.parseObject(resp); JSONObject result = new JSONObject(); result.put("id",data.getString("unionid")); result.put("nickName",data.getString("nickname")); result.put("avatar",data.getString("headimgurl")); return result; } } //微信的token只有2小時(shí)的有效期,過時(shí)需要重新獲取,所以官方提供了 //根據(jù)refresh_token 刷新獲取token的方法,本項(xiàng)目僅僅是獲取用戶 //信息,并將信息存入庫,所以兩個(gè)小時(shí)也已經(jīng)足夠了 @Override public String refreshToken(String refresh_token) { String url = String.format(REFRESH_TOKEN_URL,APP_ID,refresh_token); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url); URI uri = builder.build().encode().toUri(); ResponseEntity<JSONObject> resp = getRestTemplate().getForEntity(uri,JSONObject.class); JSONObject jsonObject = resp.getBody(); String access_token = jsonObject.getString("access_token"); return access_token; } }
步驟三:
在Controller中調(diào)用,代碼如下:
@RequestMapping(value = "/wxLoginPage",method = RequestMethod.GET) public JSONObject wxLoginPage() throws Exception { String uri = weChatAuthService.getAuthorizationUrl(); return loginPage(uri); } @RequestMapping(value = "/wechat") public void callback(String code,HttpServletRequest request,HttpServletResponse response) throws Exception { String result = weChatAuthService.getAccessToken(code); JSONObject jsonObject = JSONObject.parseObject(result); String access_token = jsonObject.getString("access_token"); String openId = jsonObject.getString("openId"); // String refresh_token = jsonObject.getString("refresh_token"); // 保存 access_token 到 cookie,兩小時(shí)過期 Cookie accessTokencookie = new Cookie("accessToken", access_token); accessTokencookie.setMaxAge(60 *2); response.addCookie(accessTokencookie); Cookie openIdCookie = new Cookie("openId", openId); openIdCookie.setMaxAge(60 *2); response.addCookie(openIdCookie); //根據(jù)openId判斷用戶是否已經(jīng)登陸過 KmsUser user = userService.getUserByCondition(openId); if (user == null) { response.sendRedirect(request.getContextPath() + "/student/html/index.min.html#/bind?type="+Constants.LOGIN_TYPE_WECHAT); } else { //如果用戶已存在,則直接登錄 response.sendRedirect(request.getContextPath() + "/student/html/index.min.html#/app/home?open_id=" + openId); } }
步驟四:
前臺(tái)js中,先請(qǐng)求auth/wxLoginPage,獲取授權(quán)地址,等用戶授權(quán)后會(huì)回調(diào)/auth/wechat,在此方法中進(jìn)行邏輯處理即可。
遇到過的坑:
1.在微信官網(wǎng)中配置回調(diào)域名的時(shí)候,不需要些http或https協(xié)議,只需要寫上域即可,例如http://baidu.com,只需要填寫baidu.com即可,如果是想要跳轉(zhuǎn)到項(xiàng)目下面的某個(gè)Controller的某個(gè)方法中,如baidu.com/auth/wechat ,配置的時(shí)候也只需要配baidu.com,不需要指定后面的auth/wechat,后面的地址在代碼中配置回調(diào)的地址的時(shí)候?qū)懮霞纯?,代碼中應(yīng)該配置為https://baidu.com/auth/wechat
2.在跳轉(zhuǎn)到授權(quán)二維碼界面的時(shí)候,會(huì)遇到有的時(shí)候二維碼出不來的狀況,這是因?yàn)榇a中的回調(diào)地址的問題,按照上面代碼中的方式配置應(yīng)該是沒有問題的
關(guān)于“Springboot怎么實(shí)現(xiàn)網(wǎng)站第三方登錄”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。
當(dāng)前題目:Springboot怎么實(shí)現(xiàn)網(wǎng)站第三方登錄
當(dāng)前鏈接:http://muchs.cn/article10/piosgo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制網(wǎng)站、微信小程序、Google、移動(dòng)網(wǎng)站建設(shè)、網(wǎng)站改版、定制開發(fā)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)