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

server/2024/10/20 15:59:59/

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/server/18169.html

相关文章

每日一题:Int 和 Integer 有什么区别❓

int 和 Integer 在 Java 中都用于表示整数&#xff0c;但它们之间有几个关键区别&#x1f53d; 类型&#x1f308; int 是一个基本数据类型&#xff0c;表示固定范围的整数值。Integer 是一个类&#xff08;class&#xff09;&#xff0c;属于 Java 的封装类&#xff0c;用于…

DRF学习之三大认证

一、认证 1、自定义认证 在前面说的 APIView 中封装了三大认证&#xff0c;分别为认证、权限、频率。认证即登录认证&#xff0c;权限表示该用户是否有权限访问接口&#xff0c;频率表示用户指定时间内能访问接口的次数。整个请求最开始的也是认证。 &#xff08;1&#xff…

Java | Leetcode Java题解之第46题全排列

题目&#xff1a; 题解&#xff1a; class Solution {public List<List<Integer>> permute(int[] nums) {List<List<Integer>> res new ArrayList<List<Integer>>();List<Integer> output new ArrayList<Integer>();for (i…

前端生成二维码

使用 Vue 生成二维码 在现代的 web 开发中&#xff0c;生成二维码是一项常见的需求。Vue 作为一个流行的前端框架&#xff0c;提供了多种方法来生成和显示二维码。本文将介绍如何使用 Vue 和一个流行的二维码生成库 qrcode 来生成二维码。 步骤 1&#xff1a;创建新的 Vue 项…

智能医疗:人工智能在医疗领域的革命性突破

在当今科技日新月异的时代&#xff0c;人工智能的蓬勃发展正在为医疗行业带来前所未有的革命性变革。其中&#xff0c;以其独特的智能诊断能力和个性化医疗服务&#xff0c;引领着医疗技术的飞速进步&#xff0c;而这一切的核心就是智能医疗系统。 智能医疗系统不仅仅是简单的…

【动态规划】Leetcode 70. 爬楼梯【简单】

爬楼梯 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢&#xff1f; 示例 1&#xff1a; 输入&#xff1a;n 2 输出&#xff1a;2 解释&#xff1a;有两种方法可以爬到楼顶。 1 阶 1 阶2 阶 解题思路 …

如何获取SSL证书?是否存在免费获取途径?

随着互联网安全意识的提升&#xff0c;HTTPS协议的使用已蔚然成风&#xff0c;无论是个人博客、新闻媒体还是社交平台&#xff0c;几乎无一例外地选择了HTTPS作为数据传输的守护者。谷歌等主流搜索引擎更是将HTTPS纳入排名权重因素&#xff0c;进一步推动了其普及。在这股潮流之…

数据结构-回溯算法

回溯算法 1.理解回溯算法的思想 基本概念 深度优先搜索:回溯算法通常采用深度优先搜索策略来遍历解空间。这意味着它会沿着一条路径尽可能深入地探索&#xff0c;直到遇到一个死胡试探与回溯:溯算法的核心在于“试错”。它会在搜索过程中做出一系列选择&#xff0c;形成一条可能…