企业微信私有化部署对接oauth2.0

2024-04-23 19:52

本文主要是介绍企业微信私有化部署对接oauth2.0,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.添加依赖:JustAuth

<dependency><groupId>me.zhyd.oauth</groupId><artifactId>JustAuth</artifactId><version>1.16.6</version>
</dependency>

2.添加 ElephantAuthSource.java

package com.elephant.devops.h5;import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.request.AuthDefaultRequest;/*** 自定义oauth2.0服务器请求地址*/
public enum ElephantAuthSource implements AuthSource {MengDianE {public String authorize() {// https://office.impc.com.cn/connect/oauth2/authorize?appid=xxx&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&agentid=AGENTID&state=STATE#wechat_redirectreturn "https://office.impc.com.cn/connect/oauth2/authorize";}public String accessToken() {return "https://office.impc.com.cn/cgi-bin/gettoken";}public String userInfo() {return "https://office.impc.com.cn/cgi-bin/user/getuserinfo";}public Class<? extends AuthDefaultRequest> getTargetClass() {return AuthMengDianRequest.class;}}
}

3.添加 AuthMengDianRequest.java

/*** 企业微信:蒙电E联授权获取用户手机号*/
@Slf4j
public class AuthMengDianRequest extends AbstractAuthWeChatEnterpriseRequest {public AuthMengDianRequest(AuthConfig config) {super(config, ElephantAuthSource.MengDianE);}public AuthMengDianRequest(AuthConfig config, AuthStateCache authStateCache) {super(config, ElephantAuthSource.MengDianE, authStateCache);}public String authorize(String state) {return UrlBuilder.fromBaseUrl(this.source.authorize()).queryParam("appid", this.config.getClientId()).queryParam("agentid", this.config.getAgentId()).queryParam("redirect_uri", GlobalAuthUtils.urlEncode(this.config.getRedirectUri())).queryParam("response_type", "code").queryParam("scope", this.getScopes(",", false, AuthScopeUtils.getDefaultScopes(AuthWeChatEnterpriseWebScope.values()))).queryParam("state", this.getRealState(state).concat("#wechat_redirect")).build();}@Overridepublic AuthResponse login(AuthCallback authCallback) {try {//this.checkCode(authCallback);//{"accessToken":"...","expireIn":7200,"refreshTokenExpireIn":0,"code":"...","snapshotUser":false}AuthToken authToken = this.getAccessToken(authCallback);//手机号=usernameAuthUser user = this.getUserInfo(authToken);return AuthResponse.builder().code(AuthResponseStatus.SUCCESS.getCode()).data(user).build();} catch (Exception var4) {Exception e = var4;Log.error("Failed to login with oauth authorization.", e);return this.responseError(e);}}protected AuthToken getAccessToken(AuthCallback authCallback) {String accessTokenUrl = this.accessTokenUrl(authCallback.getCode());log.info(">>>> accessTokenUrl: {}", accessTokenUrl);String response = this.doGetAuthorizationCode(accessTokenUrl);log.info(">>>> response: {}", response);JSONObject object = this.checkResponse(response);return AuthToken.builder().accessToken(object.getString("access_token")).expireIn(object.getIntValue("expires_in")).code(authCallback.getCode()).build();}@Overrideprotected AuthUser getUserInfo(AuthToken authToken) {String response = this.doGetUserInfo(authToken);log.info(">>>> response = {}", response);// {"UserId":"MD_chenhong","DeviceId":"xxx","errcode":0,"errmsg":"ok","usertype":5}JSONObject object = this.checkResponse(response);if (!object.containsKey("UserId")) {throw new AuthException(AuthResponseStatus.UNIDENTIFIED_PLATFORM, this.source);} else {String userId = object.getString("UserId");/* {"errcode":0,"gender":"1","is_leader_in_dept":[0],"direct_leader":[],"userid":"MD_chenhong","english_name":"","enable":1,"qr_code":"https://wwlocal.qq.com/wework_admin/userQRCode?lvc=vc78d250e697f27eba","department":[39246],"email":"","order":[4096],"isleader":0,"mobile":"13580575781","errmsg":"ok","telephone":"","positions":[""],"avatar":"","hide_mobile":0,"country_code":"86","biz_mail_alias":[],"name":"陈鸿","extattr":{"attrs":[]},"position":"","external_profile":{"external_attr":[],"external_corp_name":"内蒙古电力集团"},"status":1}*/JSONObject userDetail = this.getUserDetail(authToken.getAccessToken(), userId, null);return AuthUser.builder().rawUserInfo(userDetail).nickname(userDetail.getString("name")).avatar(userDetail.getString("avatar")).username(userDetail.getString("mobile")).uuid(userId).gender(AuthUserGender.getWechatRealGender(userDetail.getString("gender"))).token(authToken).source(this.source.toString()).build();}}protected String doGetUserInfo(AuthToken authToken) {//https://office.impc.com.cn/cgi-bin/user/getuserinfo?access_token=xxxxx&code=xxxString userInfoUrl = this.userInfoUrl(authToken);log.info(">>> userInfoUrl = {}", userInfoUrl);return HttpUtil.get(userInfoUrl);//http请求经常超时有bug//return (new HttpUtils(this.config.getHttpConfig())).get(userInfoUrl).getBody();}AuthResponse responseError(Exception e) {int errorCode = AuthResponseStatus.FAILURE.getCode();String errorMsg = e.getMessage();if (e instanceof AuthException) {AuthException authException = (AuthException)e;errorCode = authException.getErrorCode();if (StringUtils.isNotEmpty(authException.getErrorMsg())) {errorMsg = authException.getErrorMsg();}}return AuthResponse.builder().code(errorCode).msg(errorMsg).build();}private JSONObject checkResponse(String response) {JSONObject object = JSONObject.parseObject(response);if (object.containsKey("errcode") && object.getIntValue("errcode") != 0) {throw new AuthException(object.getString("errmsg"), this.source);} else {return object;}}private JSONObject getUserDetail(String accessToken, String userId, String userTicket) {String userInfoUrl = UrlBuilder.fromBaseUrl("https://office.impc.com.cn/cgi-bin/user/get").queryParam("access_token", accessToken).queryParam("userid", userId).build();String userInfoResponse = (new HttpUtils(this.config.getHttpConfig())).get(userInfoUrl).getBody();JSONObject userInfo = this.checkResponse(userInfoResponse);if (StringUtils.isNotEmpty(userTicket)) {String userDetailUrl = UrlBuilder.fromBaseUrl("https://office.impc.com.cn/cgi-bin/auth/getuserdetail").queryParam("access_token", accessToken).build();JSONObject param = new JSONObject();param.put("user_ticket", userTicket);String userDetailResponse = (new HttpUtils(this.config.getHttpConfig())).post(userDetailUrl, param.toJSONString()).getBody();JSONObject userDetail = this.checkResponse(userDetailResponse);userInfo.putAll(userDetail);}return userInfo;}
}

4.添加 Oauth2Controller.java

@RestController
@RequestMapping("/api/pub/oauth2")
@Api(value = "Oauth2Controller ", tags = "蒙电E家oauth2")
@Slf4j
public class Oauth2Controller extends BaseController {@Autowiredprivate AuthService authService;/*** localhost:7061/api/pub/oauth2/render* 跳转进入:* https://open.weixin.qq.com/connect/oauth2/authorize?appid=xxx&agentid=10xxx&redirect_uri=https://office.impc.com.cn/cgi-bin/gettoken&response_type=code&scope=snsapi_base&state=xxxx#wechat_redirect* https://open.weixin.qq.com/connect/oauth2/authorize?appid=xxx&agentid=10xxx&redirect_uri=https://office.impc.com.cn&response_type=code&scope=snsapi_base&state=xxxx#wechat_redirect* @param response* @throws IOException*/@GetMapping("/render")public void renderAuth(HttpServletResponse response) throws IOException {AuthRequest authRequest = getAuthRequest();response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));}/*** 查询 state* localhost:7061/api/pub/oauth2/getState* @return*/@GetMapping("/getState")public Result getState() {AuthRequest authRequest = getAuthRequest();String state = AuthStateUtils.createState();String url = authRequest.authorize(state);log.debug("url = {}", url);return Result.success(state);}/*** localhost:7061/api/pub/oauth2/callback?code=xxx&state=xxx* @param callback* @return*/@GetMapping("/callback")public Result<AuthVO> callback(AuthCallback callback) {AuthRequest authRequest = getAuthRequest();try {AuthResponse response = authRequest.login(callback);log.info(">>>> response = {}", JSONUtil.toJsonStr(response));int code = response.getCode();if(code == 2000) {AuthUser data = (AuthUser) response.getData();String phone = data.getUsername();AuthVO authVO = authService.loginByPhone(phone);if(authVO != null) {return Result.success(authVO);}else {AuthVO bean = new AuthVO();bean.setToken("-1");return Result.success(bean);}}}catch (Exception e){e.printStackTrace();}return Result.fail("500", "系统异常");}private AuthRequest getAuthRequest() {return new AuthMengDianRequest(AuthConfig.builder().clientId("xxxx").clientSecret("xxxxxxx").redirectUri("https://office.impc.com.cn").agentId("xxxxx").build());}}

这篇关于企业微信私有化部署对接oauth2.0的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/929726

相关文章

Python对接支付宝支付之使用AliPay实现的详细操作指南

《Python对接支付宝支付之使用AliPay实现的详细操作指南》支付宝没有提供PythonSDK,但是强大的github就有提供python-alipay-sdk,封装里很多复杂操作,使用这个我们就... 目录一、引言二、准备工作2.1 支付宝开放平台入驻与应用创建2.2 密钥生成与配置2.3 安装ali

MySQL 主从复制部署及验证(示例详解)

《MySQL主从复制部署及验证(示例详解)》本文介绍MySQL主从复制部署步骤及学校管理数据库创建脚本,包含表结构设计、示例数据插入和查询语句,用于验证主从同步功能,感兴趣的朋友一起看看吧... 目录mysql 主从复制部署指南部署步骤1.环境准备2. 主服务器配置3. 创建复制用户4. 获取主服务器状态5

Spring Boot 结合 WxJava 实现文章上传微信公众号草稿箱与群发

《SpringBoot结合WxJava实现文章上传微信公众号草稿箱与群发》本文将详细介绍如何使用SpringBoot框架结合WxJava开发工具包,实现文章上传到微信公众号草稿箱以及群发功能,... 目录一、项目环境准备1.1 开发环境1.2 微信公众号准备二、Spring Boot 项目搭建2.1 创建

golang程序打包成脚本部署到Linux系统方式

《golang程序打包成脚本部署到Linux系统方式》Golang程序通过本地编译(设置GOOS为linux生成无后缀二进制文件),上传至Linux服务器后赋权执行,使用nohup命令实现后台运行,完... 目录本地编译golang程序上传Golang二进制文件到linux服务器总结本地编译Golang程序

如何在Ubuntu 24.04上部署Zabbix 7.0对服务器进行监控

《如何在Ubuntu24.04上部署Zabbix7.0对服务器进行监控》在Ubuntu24.04上部署Zabbix7.0监控阿里云ECS服务器,需配置MariaDB数据库、开放10050/1005... 目录软硬件信息部署步骤步骤 1:安装并配置mariadb步骤 2:安装Zabbix 7.0 Server

java向微信服务号发送消息的完整步骤实例

《java向微信服务号发送消息的完整步骤实例》:本文主要介绍java向微信服务号发送消息的相关资料,包括申请测试号获取appID/appsecret、关注公众号获取openID、配置消息模板及代码... 目录步骤1. 申请测试系统2. 公众号账号信息3. 关注测试号二维码4. 消息模板接口5. Java测试

Python基于微信OCR引擎实现高效图片文字识别

《Python基于微信OCR引擎实现高效图片文字识别》这篇文章主要为大家详细介绍了一款基于微信OCR引擎的图片文字识别桌面应用开发全过程,可以实现从图片拖拽识别到文字提取,感兴趣的小伙伴可以跟随小编一... 目录一、项目概述1.1 开发背景1.2 技术选型1.3 核心优势二、功能详解2.1 核心功能模块2.

java对接海康摄像头的完整步骤记录

《java对接海康摄像头的完整步骤记录》在Java中调用海康威视摄像头通常需要使用海康威视提供的SDK,下面这篇文章主要给大家介绍了关于java对接海康摄像头的完整步骤,文中通过代码介绍的非常详细,需... 目录一、开发环境准备二、实现Java调用设备接口(一)加载动态链接库(二)结构体、接口重定义1.类型

如何基于Python开发一个微信自动化工具

《如何基于Python开发一个微信自动化工具》在当今数字化办公场景中,自动化工具已成为提升工作效率的利器,本文将深入剖析一个基于Python的微信自动化工具开发全过程,有需要的小伙伴可以了解下... 目录概述功能全景1. 核心功能模块2. 特色功能效果展示1. 主界面概览2. 定时任务配置3. 操作日志演示

Redis迷你版微信抢红包实战

《Redis迷你版微信抢红包实战》本文主要介绍了Redis迷你版微信抢红包实战... 目录1 思路分析1.1hCckRX 流程1.2 注意点①拆红包:二倍均值算法②发红包:list③抢红包&记录:hset2 代码实现2.1 拆红包splitRedPacket2.2 发红包sendRedPacket2.3 抢