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

embedded/2024/9/22 22:59:13/

1.添加依赖:JustAuth

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

2.添加 ElephantAuthSource.java

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

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

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());}}


http://www.ppmy.cn/embedded/18815.html

相关文章

缓存相关问题:雪崩、穿透、预热、更新、降级的深度解析

✨✨祝屏幕前的小伙伴们每天都有好运相伴左右✨✨ &#x1f388;&#x1f388;作者主页&#xff1a; 喔的嘛呀&#x1f388;&#x1f388; 目录 1. 缓存雪崩 1.1 问题描述 1.2 解决方案 1.2.1 加锁防止并发重建缓存 2. 缓存穿透 2.1 问题描述 2.2 解决方案 2.2.1 布隆过…

Laravel 6 - 第十一章 中间件

​ 文章目录 Laravel 6 - 第一章 简介 Laravel 6 - 第二章 项目搭建 Laravel 6 - 第三章 文件夹结构 Laravel 6 - 第四章 生命周期 Laravel 6 - 第五章 控制反转和依赖注入 Laravel 6 - 第六章 服务容器 Laravel 6 - 第七章 服务提供者 Laravel 6 - 第八章 门面 Laravel 6 - …

感觉眩晕就以为高血压犯了?如果伴有耳鸣,请警惕这种疾病

高血压被称为“无形杀手”&#xff0c;我国调查研究显示每3位成年人中就有1位高血压患者&#xff0c;典型表现为头痛、心悸耳鸣等&#xff0c;偶尔也存在阵发性眩晕等不典型表现。当出现耳鸣、眩晕等症状时切忌想当然以为是高血压&#xff0c;尤其是耳鸣和眩晕两者同时出现而且…

Windows如何安装spark

Apache Spark是一个开源的大数据处理框架&#xff0c;旨在提供高效、通用和易用的大数据处理引擎。它最初由加州大学伯克利分校AMPLab开发&#xff0c;并于2010年开源。 Spark提供了一个基于内存的计算引擎&#xff0c;可以在大规模数据集上执行高速的数据处理任务。相比传统的…

MySQL B+索引的工作原理及应用

引言 在数据库系统中&#xff0c;索引是优化查询、提高性能的关键技术之一。特别是在MySQL数据库中&#xff0c;B树索引作为最常用的索引类型&#xff0c;对数据库性能有着至关重要的影响。本文旨简单解析MySQL中B树索引的工作原理&#xff0c;帮助学生朋友们更好地理解和利用…

windows驱动开发-I/O请求(一)

I/O请求是内核中非常重要的部分&#xff0c;所有的驱动功能都使用I/O请求来交互&#xff0c;故理解了I/O请求也就理解了驱动的工作原理。 DeviceIoControl 这个函数主要就是用于发送I/O请求: BOOL DeviceIoControl (HANDLE hDevice, // CreateFile返回的设备句柄…

ShardingSphere 5.x 系列【25】 数据分片原理之 SQL 解析

有道无术,术尚可求,有术无道,止于术。 本系列Spring Boot 版本 3.1.0 本系列ShardingSphere 版本 5.4.0 源码地址:https://gitee.com/pearl-organization/study-sharding-sphere-demo 文章目录 1. 分片执行流程1.1 Simple Push Down1.2 SQL Federation2. SQL 解析2.1 解析…

商城数据库88张表结构(十二)

DDL 45.商城信息表 CREATE TABLE wang_messages (id int(11) NOT NULL AUTO_INCREMENT COMMENT 自增id,msgType tinyint(4) NOT NULL DEFAULT 0 COMMENT 消息类型(0:后台手工发送的消息 1:系统自动发的消息),sendUserid int(11) NOT NULL DEFAULT 0 COMMENT 发送者id,receiveU…