Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the third Party Login of the website by Springboot

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of "how to realize the third party login of the website by Springboot". The editor shows you the operation process through the actual case, the operation method is simple and fast, and the practicality is strong. I hope that this article "how to realize the third party login of the Springboot website" can help you solve the problem.

Step 1: create an interface that inherits AuthService, WeChatAuthService, as follows

Public interface WeChatAuthService extends AuthService {public JSONObject getUserInfo (String accessToken, String openId);}

Step 2: the specific implementation of WeChatService is as follows

@ Servicepublic class WeChatAuthServiceImpl extends DefaultAuthServiceImpl implements WeChatAuthService {private Logger logger = LoggerFactory.getLogger (WeChatAuthServiceImpl.class); / / request this address to jump to the QR code login interface 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";" / / get the URL private static final String ACCESSTOKE_OPENID_URL of user openid and access--toke = "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"; " / / callback domain @ 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 ("failed to get token, msg =" + resp) }} / / in Wechat interface, token and openId are returned together, so this method does not need to implement @ 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 ("error in obtaining user information, 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 }} / / the token of Wechat is only valid for 2 hours and needs to be reacquired when it becomes obsolete, so officials have provided / / the method to obtain token according to refresh_token refresh. This project only acquires user / / information and stores it in the database, so two hours is enough for @ 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 resp = getRestTemplate (). GetForEntity (uri,JSONObject.class); JSONObject jsonObject = resp.getBody (); String access_token = jsonObject.getString ("access_token"); return access_token;}}

Step 3:

Called in Controller, the code is as follows:

@ 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"); / / Save access_token to cookie, two-hour expiration 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) / / judge whether the user has logged in according to openId KmsUser user = userService.getUserByCondition (openId); if (user = = null) {response.sendRedirect (request.getContextPath () + "/ student/html/index.min.html#/bind?type=" + Constants.LOGIN_TYPE_WECHAT) } else {/ / if the user already exists, log in directly to response.sendRedirect (request.getContextPath () + "/ student/html/index.min.html#/app/home?open_id=" + openId);}}

Step 4:

In the foreground js, first request the auth/wxLoginPage to obtain the authorized address, and then call back / auth/wechat after the user is authorized. You can do logical processing in this method.

The pit you have encountered:

1. When configuring a callback domain name in Wechat's official website, you don't need some http or https protocols, you just need to write the domain, such as http://baidu.com, and you only need to enter baidu.com. If you want to jump to a method of Controller under the project, such as baidu.com/auth/wechat, you only need to configure it with baidu.com, instead of specifying the following auth/wechat. The following address can be written when the callback address is configured in the code, and the code should be configured as https://baidu.com/auth/wechat

two。 When you jump to the authorized QR code interface, you will encounter the situation that sometimes the QR code will not come out. This is because of the callback address problem in the code, and there should be no problem with configuring it according to the way in the above code.

This is the end of the content about "how to achieve third-party login on the website by Springboot". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report