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
@Service public class WeChatAuthServiceImpl extends DefaultAuthServiceImpl implements WeChatAuthService { private Logger logger = LoggerFactory.getLogger(WeChatAuthServiceImpl.class); //请求此地址即跳转到二维码登录界面 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"; //回调域名 @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是一起返回,故此方法不需实现 @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("获取用户信息错误,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小时的有效期,过时需要重新获取,所以官方提供了 //根据refresh_token 刷新获取token的方法,本项目仅仅是获取用户 //信息,并将信息存入库,所以两个小时也已经足够了 @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; } }</jsonobject>
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"); // 保存 access_token 到 cookie,两小时过期 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); //根据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 { //如果用户已存在,则直接登录 response.sendRedirect(request.getContextPath() + "/student/html/index.min.html#/app/home?open_id=" + openId); } }
Step 4:
Front-end js , first request auth/wxLoginPage to obtain the authorization address. After the user authorizes it, /auth/wechat will be called back. Just perform logical processing in this method.
Pitfalls encountered:
1. When configuring the callback domain name on the WeChat official website, there is no need for some http or https protocol, you only need to write the domain, for example http://baidu.com, you only need to fill in baidu.com. If you want to jump to a method of a Controller under the project, such as baidu.com/auth/wechat, just configure it. You need to configure baidu.com, and you don’t need to specify the subsequent auth/wechat. You can just write the subsequent address when configuring the callback address in the code. The code should be configured as https://baidu.com/auth/wechat
2. When jumping to the authorization QR code interface, you will sometimes encounter a situation where the QR code cannot be displayed. This is because of the callback address in the code. According to the configuration in the above code, it should be No problem
The above is the detailed content of How Springboot implements third-party login to the website. For more information, please follow other related articles on the PHP Chinese website!

Canal工作原理Canal模拟MySQLslave的交互协议,伪装自己为MySQLslave,向MySQLmaster发送dump协议MySQLmaster收到dump请求,开始推送binarylog给slave(也就是Canal)Canal解析binarylog对象(原始为byte流)MySQL打开binlog模式在MySQL配置文件my.cnf设置如下信息:[mysqld]#打开binloglog-bin=mysql-bin#选择ROW(行)模式binlog-format=ROW#配置My

前言SSE简单的来说就是服务器主动向前端推送数据的一种技术,它是单向的,也就是说前端是不能向服务器发送数据的。SSE适用于消息推送,监控等只需要服务器推送数据的场景中,下面是使用SpringBoot来实现一个简单的模拟向前端推动进度数据,前端页面接受后展示进度条。服务端在SpringBoot中使用时需要注意,最好使用SpringWeb提供的SseEmitter这个类来进行操作,我在刚开始时使用网上说的将Content-Type设置为text-stream这种方式发现每次前端每次都会重新创建接。最

一、手机扫二维码登录的原理二维码扫码登录是一种基于OAuth3.0协议的授权登录方式。在这种方式下,应用程序不需要获取用户的用户名和密码,只需要获取用户的授权即可。二维码扫码登录主要有以下几个步骤:应用程序生成一个二维码,并将该二维码展示给用户。用户使用扫码工具扫描该二维码,并在授权页面中授权。用户授权后,应用程序会获取一个授权码。应用程序使用该授权码向授权服务器请求访问令牌。授权服务器返回一个访问令牌给应用程序。应用程序使用该访问令牌访问资源服务器。通过以上步骤,二维码扫码登录可以实现用户的快

1.springboot2.x及以上版本在SpringBoot2.xAOP中会默认使用Cglib来实现,但是Spring5中默认还是使用jdk动态代理。SpringAOP默认使用JDK动态代理,如果对象没有实现接口,则使用CGLIB代理。当然,也可以强制使用CGLIB代理。在SpringBoot中,通过AopAutoConfiguration来自动装配AOP.2.Springboot1.xSpringboot1.xAOP默认还是使用JDK动态代理的3.SpringBoot2.x为何默认使用Cgl

我们使用jasypt最新版本对敏感信息进行加解密。1.在项目pom文件中加入如下依赖:com.github.ulisesbocchiojasypt-spring-boot-starter3.0.32.创建加解密公用类:packagecom.myproject.common.utils;importorg.jasypt.encryption.pbe.PooledPBEStringEncryptor;importorg.jasypt.encryption.pbe.config.SimpleStrin

知识准备需要理解ApachePOI遵循的标准(OfficeOpenXML(OOXML)标准和微软的OLE2复合文档格式(OLE2)),这将对应着API的依赖包。什么是POIApachePOI是用Java编写的免费开源的跨平台的JavaAPI,ApachePOI提供API给Java程序对MicrosoftOffice格式档案读和写的功能。POI为“PoorObfuscationImplementation”的首字母缩写,意为“简洁版的模糊实现”。ApachePOI是创建和维护操作各种符合Offic

1.首先新建一个shiroConfigshiro的配置类,代码如下:@ConfigurationpublicclassSpringShiroConfig{/***@paramrealms这儿使用接口集合是为了实现多验证登录时使用的*@return*/@BeanpublicSecurityManagersecurityManager(Collectionrealms){DefaultWebSecurityManagersManager=newDefaultWebSecurityManager();

一、定义视频上传请求接口publicAjaxResultvideoUploadFile(MultipartFilefile){try{if(null==file||file.isEmpty()){returnAjaxResult.error("文件为空");}StringossFilePrefix=StringUtils.genUUID();StringfileName=ossFilePrefix+"-"+file.getOriginalFilename(


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
