企业微信私有化部署对接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

相关文章

闲置电脑也能活出第二春?鲁大师AiNAS让你动动手指就能轻松部署

对于大多数人而言,在这个“数据爆炸”的时代或多或少都遇到过存储告急的情况,这使得“存储焦虑”不再是个别现象,而将会是随着软件的不断臃肿而越来越普遍的情况。从不少手机厂商都开始将存储上限提升至1TB可以见得,我们似乎正处在互联网信息飞速增长的阶段,对于存储的需求也将会不断扩大。对于苹果用户而言,这一问题愈发严峻,毕竟512GB和1TB版本的iPhone可不是人人都消费得起的,因此成熟的外置存储方案开

W外链微信推广短连接怎么做?

制作微信推广链接的难点分析 一、内容创作难度 制作微信推广链接时,首先需要创作有吸引力的内容。这不仅要求内容本身有趣、有价值,还要能够激起人们的分享欲望。对于许多企业和个人来说,尤其是那些缺乏创意和写作能力的人来说,这是制作微信推广链接的一大难点。 二、精准定位难度 微信用户群体庞大,不同用户的需求和兴趣各异。因此,制作推广链接时需要精准定位目标受众,以便更有效地吸引他们点击并分享链接

Hadoop企业开发案例调优场景

需求 (1)需求:从1G数据中,统计每个单词出现次数。服务器3台,每台配置4G内存,4核CPU,4线程。 (2)需求分析: 1G / 128m = 8个MapTask;1个ReduceTask;1个mrAppMaster 平均每个节点运行10个 / 3台 ≈ 3个任务(4    3    3) HDFS参数调优 (1)修改:hadoop-env.sh export HDFS_NAMENOD

阿里开源语音识别SenseVoiceWindows环境部署

SenseVoice介绍 SenseVoice 专注于高精度多语言语音识别、情感辨识和音频事件检测多语言识别: 采用超过 40 万小时数据训练,支持超过 50 种语言,识别效果上优于 Whisper 模型。富文本识别:具备优秀的情感识别,能够在测试数据上达到和超过目前最佳情感识别模型的效果。支持声音事件检测能力,支持音乐、掌声、笑声、哭声、咳嗽、喷嚏等多种常见人机交互事件进行检测。高效推

在 Windows 上部署 gitblit

在 Windows 上部署 gitblit 在 Windows 上部署 gitblit 缘起gitblit 是什么安装JDK部署 gitblit 下载 gitblit 并解压配置登录注册为 windows 服务 修改 installService.cmd 文件运行 installService.cmd运行 gitblitw.exe查看 services.msc 缘起

Solr部署如何启动

Solr部署如何启动 Posted on 一月 10, 2013 in:  Solr入门 | 评论关闭 我刚接触solr,我要怎么启动,这是群里的朋友问得比较多的问题, solr最新版本下载地址: http://www.apache.org/dyn/closer.cgi/lucene/solr/ 1、准备环境 建立一个solr目录,把solr压缩包example目录下的内容复制

如何更优雅地对接第三方API

如何更优雅地对接第三方API 本文所有示例完整代码地址:https://github.com/yu-linfeng/BlogRepositories/tree/master/repositories/third 我们在日常开发过程中,有不少场景会对接第三方的API,例如第三方账号登录,第三方服务等等。第三方服务会提供API或者SDK,我依稀记得早些年Maven还没那么广泛使用,通常要对接第三方

uniapp设置微信小程序的交互反馈

链接:uni.showToast(OBJECT) | uni-app官网 (dcloud.net.cn) 设置操作成功的弹窗: title是我们弹窗提示的文字 showToast是我们在加载的时候进入就会弹出的提示。 2.设置失败的提示窗口和标签 icon:'error'是设置我们失败的logo 设置的文字上限是7个文字,如果需要设置的提示文字过长就需要设置icon并给

Spring Roo 实站( 一 )部署安装 第一个示例程序

转自:http://blog.csdn.net/jun55xiu/article/details/9380213 一:安装 注:可以参与官网spring-roo: static.springsource.org/spring-roo/reference/html/intro.html#intro-exploring-sampleROO_OPTS http://stati

828华为云征文|华为云Flexus X实例docker部署rancher并构建k8s集群

828华为云征文|华为云Flexus X实例docker部署rancher并构建k8s集群 华为云最近正在举办828 B2B企业节,Flexus X实例的促销力度非常大,特别适合那些对算力性能有高要求的小伙伴。如果你有自建MySQL、Redis、Nginx等服务的需求,一定不要错过这个机会。赶紧去看看吧! 什么是华为云Flexus X实例 华为云Flexus X实例云服务是新一代开箱即用、体