本文主要是介绍企业微信私有化部署对接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的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!