提交 0d4e52d6 编写于 作者: 不合群的混子's avatar 不合群的混子

移除 UrlBuilder

上级 72792c3c
...@@ -14,8 +14,8 @@ import me.zhyd.oauth.model.AuthCallback; ...@@ -14,8 +14,8 @@ import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthToken; import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser; import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.model.AuthUserGender; import me.zhyd.oauth.model.AuthUserGender;
import me.zhyd.oauth.url.AuthAlipayUrlBuilder;
import me.zhyd.oauth.utils.StringUtils; import me.zhyd.oauth.utils.StringUtils;
import me.zhyd.oauth.utils.UrlBuilder;
/** /**
* 支付宝登录 * 支付宝登录
...@@ -29,9 +29,9 @@ public class AuthAlipayRequest extends AuthDefaultRequest { ...@@ -29,9 +29,9 @@ public class AuthAlipayRequest extends AuthDefaultRequest {
private AlipayClient alipayClient; private AlipayClient alipayClient;
public AuthAlipayRequest(AuthConfig config) { public AuthAlipayRequest(AuthConfig config) {
super(config, AuthSource.ALIPAY, new AuthAlipayUrlBuilder()); super(config, AuthSource.ALIPAY);
this.alipayClient = new DefaultAlipayClient(AuthSource.ALIPAY.accessToken(), config.getClientId(), config.getClientSecret(), "json", "UTF-8", config this.alipayClient = new DefaultAlipayClient(AuthSource.ALIPAY.accessToken(), config.getClientId(), config.getClientSecret(), "json", "UTF-8", config
.getAlipayPublicKey(), "RSA2"); .getAlipayPublicKey(), "RSA2");
} }
@Override @Override
...@@ -49,11 +49,11 @@ public class AuthAlipayRequest extends AuthDefaultRequest { ...@@ -49,11 +49,11 @@ public class AuthAlipayRequest extends AuthDefaultRequest {
throw new AuthException(response.getSubMsg()); throw new AuthException(response.getSubMsg());
} }
return AuthToken.builder() return AuthToken.builder()
.accessToken(response.getAccessToken()) .accessToken(response.getAccessToken())
.uid(response.getUserId()) .uid(response.getUserId())
.expireIn(Integer.parseInt(response.getExpiresIn())) .expireIn(Integer.parseInt(response.getExpiresIn()))
.refreshToken(response.getRefreshToken()) .refreshToken(response.getRefreshToken())
.build(); .build();
} }
@Override @Override
...@@ -70,19 +70,33 @@ public class AuthAlipayRequest extends AuthDefaultRequest { ...@@ -70,19 +70,33 @@ public class AuthAlipayRequest extends AuthDefaultRequest {
throw new AuthException(response.getSubMsg()); throw new AuthException(response.getSubMsg());
} }
String province = response.getProvince(), String province = response.getProvince(), city = response.getCity();
city = response.getCity();
String location = String.format("%s %s", StringUtils.isEmpty(province) ? "" : province, StringUtils.isEmpty(city) ? "" : city); String location = String.format("%s %s", StringUtils.isEmpty(province) ? "" : province, StringUtils.isEmpty(city) ? "" : city);
return AuthUser.builder() return AuthUser.builder()
.uuid(response.getUserId()) .uuid(response.getUserId())
.username(StringUtils.isEmpty(response.getUserName()) ? response.getNickName() : response.getUserName()) .username(StringUtils.isEmpty(response.getUserName()) ? response.getNickName() : response.getUserName())
.nickname(response.getNickName()) .nickname(response.getNickName())
.avatar(response.getAvatar()) .avatar(response.getAvatar())
.location(location) .location(location)
.gender(AuthUserGender.getRealGender(response.getGender())) .gender(AuthUserGender.getRealGender(response.getGender()))
.token(authToken) .token(authToken)
.source(AuthSource.ALIPAY) .source(AuthSource.ALIPAY)
.build(); .build();
}
/**
* 返回认证url,可自行跳转页面
*
* @return 返回授权地址
*/
@Override
public String authorize() {
return UrlBuilder.fromBaseUrl(source.authorize())
.queryParam("app_id", config.getClientId())
.queryParam("scope", "auth_user")
.queryParam("redirect_uri", config.getRedirectUri())
.queryParam("state", getRealState(config.getState()))
.build();
} }
} }
...@@ -8,8 +8,7 @@ import me.zhyd.oauth.config.AuthSource; ...@@ -8,8 +8,7 @@ import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.enums.AuthBaiduErrorCode; import me.zhyd.oauth.enums.AuthBaiduErrorCode;
import me.zhyd.oauth.exception.AuthException; import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.*; import me.zhyd.oauth.model.*;
import me.zhyd.oauth.url.AuthBaiduUrlBuilder; import me.zhyd.oauth.utils.UrlBuilder;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
/** /**
* 百度账号登录 * 百度账号登录
...@@ -21,32 +20,28 @@ import me.zhyd.oauth.url.entity.AuthUserInfoEntity; ...@@ -21,32 +20,28 @@ import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
public class AuthBaiduRequest extends AuthDefaultRequest { public class AuthBaiduRequest extends AuthDefaultRequest {
public AuthBaiduRequest(AuthConfig config) { public AuthBaiduRequest(AuthConfig config) {
super(config, AuthSource.BAIDU, new AuthBaiduUrlBuilder()); super(config, AuthSource.BAIDU);
} }
@Override @Override
protected AuthToken getAccessToken(AuthCallback authCallback) { protected AuthToken getAccessToken(AuthCallback authCallback) {
String accessTokenUrl = this.urlBuilder.getAccessTokenUrl(authCallback.getCode()); HttpResponse response = doPostAuthorizationCode(authCallback.getCode());
HttpResponse response = HttpRequest.post(accessTokenUrl).execute();
JSONObject accessTokenObject = JSONObject.parseObject(response.body()); JSONObject accessTokenObject = JSONObject.parseObject(response.body());
AuthBaiduErrorCode errorCode = AuthBaiduErrorCode.getErrorCode(accessTokenObject.getString("error")); AuthBaiduErrorCode errorCode = AuthBaiduErrorCode.getErrorCode(accessTokenObject.getString("error"));
if (AuthBaiduErrorCode.OK != errorCode) { if (AuthBaiduErrorCode.OK != errorCode) {
throw new AuthException(errorCode.getDesc()); throw new AuthException(errorCode.getDesc());
} }
return AuthToken.builder() return AuthToken.builder()
.accessToken(accessTokenObject.getString("access_token")) .accessToken(accessTokenObject.getString("access_token"))
.refreshToken(accessTokenObject.getString("refresh_token")) .refreshToken(accessTokenObject.getString("refresh_token"))
.scope(accessTokenObject.getString("scope")) .scope(accessTokenObject.getString("scope"))
.expireIn(accessTokenObject.getIntValue("expires_in")) .expireIn(accessTokenObject.getIntValue("expires_in"))
.build(); .build();
} }
@Override @Override
protected AuthUser getUserInfo(AuthToken authToken) { protected AuthUser getUserInfo(AuthToken authToken) {
String accessToken = authToken.getAccessToken(); HttpResponse response = doGetUserInfo(authToken);
HttpResponse response = HttpRequest.get(this.urlBuilder.getUserInfoUrl(AuthUserInfoEntity.builder()
.accessToken(accessToken)
.build())).execute();
String userInfo = response.body(); String userInfo = response.body();
JSONObject object = JSONObject.parseObject(userInfo); JSONObject object = JSONObject.parseObject(userInfo);
AuthBaiduErrorCode errorCode = AuthBaiduErrorCode.getErrorCode(object.getString("error")); AuthBaiduErrorCode errorCode = AuthBaiduErrorCode.getErrorCode(object.getString("error"));
...@@ -54,29 +49,46 @@ public class AuthBaiduRequest extends AuthDefaultRequest { ...@@ -54,29 +49,46 @@ public class AuthBaiduRequest extends AuthDefaultRequest {
throw new AuthException(errorCode.getDesc()); throw new AuthException(errorCode.getDesc());
} }
return AuthUser.builder() return AuthUser.builder()
.uuid(object.getString("userid")) .uuid(object.getString("userid"))
.username(object.getString("username")) .username(object.getString("username"))
.nickname(object.getString("username")) .nickname(object.getString("username"))
.gender(AuthUserGender.getRealGender(object.getString("sex"))) .gender(AuthUserGender.getRealGender(object.getString("sex")))
.token(authToken) .token(authToken)
.source(AuthSource.BAIDU) .source(AuthSource.BAIDU)
.build(); .build();
} }
@Override @Override
public AuthResponse revoke(AuthToken authToken) { public AuthResponse revoke(AuthToken authToken) {
String accessToken = authToken.getAccessToken(); String accessToken = authToken.getAccessToken();
HttpResponse response = HttpRequest.get(this.urlBuilder.getRevokeUrl(accessToken)).execute(); HttpResponse response = HttpRequest.get(UrlBuilder.fromBaseUrl(source.revoke())
.queryParam("access_token", accessToken)
.build()).execute();
String userInfo = response.body(); String userInfo = response.body();
JSONObject object = JSONObject.parseObject(userInfo); JSONObject object = JSONObject.parseObject(userInfo);
if (object.containsKey("error_code")) { if (object.containsKey("error_code")) {
return AuthResponse.builder() return AuthResponse.builder()
.code(AuthResponseStatus.FAILURE.getCode()) .code(AuthResponseStatus.FAILURE.getCode())
.msg(object.getString("error_msg")) .msg(object.getString("error_msg"))
.build(); .build();
} }
AuthResponseStatus status = object.getIntValue("result") == 1 ? AuthResponseStatus.SUCCESS : AuthResponseStatus.FAILURE; AuthResponseStatus status = object.getIntValue("result") == 1 ? AuthResponseStatus.SUCCESS : AuthResponseStatus.FAILURE;
return AuthResponse.builder().code(status.getCode()).msg(status.getMsg()).build(); return AuthResponse.builder().code(status.getCode()).msg(status.getMsg()).build();
} }
/**
* 返回认证url,可自行跳转页面
*
* @return 返回授权地址
*/
@Override
public String authorize() {
return UrlBuilder.fromBaseUrl(source.authorize())
.queryParam("response_type", "code")
.queryParam("client_id", config.getClientId())
.queryParam("redirect_uri", config.getRedirectUri())
.queryParam("display", "popup")
.queryParam("state", getRealState(config.getState()))
.build();
}
} }
...@@ -10,8 +10,7 @@ import me.zhyd.oauth.model.AuthCallback; ...@@ -10,8 +10,7 @@ import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthToken; import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser; import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.model.AuthUserGender; import me.zhyd.oauth.model.AuthUserGender;
import me.zhyd.oauth.url.AuthCodingUrlBuilder; import me.zhyd.oauth.utils.UrlBuilder;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
/** /**
* Cooding登录 * Cooding登录
...@@ -23,30 +22,26 @@ import me.zhyd.oauth.url.entity.AuthUserInfoEntity; ...@@ -23,30 +22,26 @@ import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
public class AuthCodingRequest extends AuthDefaultRequest { public class AuthCodingRequest extends AuthDefaultRequest {
public AuthCodingRequest(AuthConfig config) { public AuthCodingRequest(AuthConfig config) {
super(config, AuthSource.CODING, new AuthCodingUrlBuilder()); super(config, AuthSource.CODING);
} }
@Override @Override
protected AuthToken getAccessToken(AuthCallback authCallback) { protected AuthToken getAccessToken(AuthCallback authCallback) {
String accessTokenUrl = this.urlBuilder.getAccessTokenUrl(authCallback.getCode()); HttpResponse response = doGetAuthorizationCode(authCallback.getCode());
HttpResponse response = HttpRequest.get(accessTokenUrl).execute();
JSONObject accessTokenObject = JSONObject.parseObject(response.body()); JSONObject accessTokenObject = JSONObject.parseObject(response.body());
if (accessTokenObject.getIntValue("code") != 0) { if (accessTokenObject.getIntValue("code") != 0) {
throw new AuthException("Unable to get token from coding using code [" + authCallback.getCode() + "]: " + accessTokenObject); throw new AuthException("Unable to get token from coding using code [" + authCallback.getCode() + "]: " + accessTokenObject);
} }
return AuthToken.builder() return AuthToken.builder()
.accessToken(accessTokenObject.getString("access_token")) .accessToken(accessTokenObject.getString("access_token"))
.expireIn(accessTokenObject.getIntValue("expires_in")) .expireIn(accessTokenObject.getIntValue("expires_in"))
.refreshToken(accessTokenObject.getString("refresh_token")) .refreshToken(accessTokenObject.getString("refresh_token"))
.build(); .build();
} }
@Override @Override
protected AuthUser getUserInfo(AuthToken authToken) { protected AuthUser getUserInfo(AuthToken authToken) {
String accessToken = authToken.getAccessToken(); HttpResponse response = doGetUserInfo(authToken);
HttpResponse response = HttpRequest.get(this.urlBuilder.getUserInfoUrl(AuthUserInfoEntity.builder()
.accessToken(accessToken)
.build())).execute();
JSONObject object = JSONObject.parseObject(response.body()); JSONObject object = JSONObject.parseObject(response.body());
if (object.getIntValue("code") != 0) { if (object.getIntValue("code") != 0) {
throw new AuthException(object.getString("msg")); throw new AuthException(object.getString("msg"));
...@@ -54,18 +49,34 @@ public class AuthCodingRequest extends AuthDefaultRequest { ...@@ -54,18 +49,34 @@ public class AuthCodingRequest extends AuthDefaultRequest {
object = object.getJSONObject("data"); object = object.getJSONObject("data");
return AuthUser.builder() return AuthUser.builder()
.uuid(object.getString("id")) .uuid(object.getString("id"))
.username(object.getString("name")) .username(object.getString("name"))
.avatar("https://coding.net/" + object.getString("avatar")) .avatar("https://coding.net/" + object.getString("avatar"))
.blog("https://coding.net/" + object.getString("path")) .blog("https://coding.net/" + object.getString("path"))
.nickname(object.getString("name")) .nickname(object.getString("name"))
.company(object.getString("company")) .company(object.getString("company"))
.location(object.getString("location")) .location(object.getString("location"))
.gender(AuthUserGender.getRealGender(object.getString("sex"))) .gender(AuthUserGender.getRealGender(object.getString("sex")))
.email(object.getString("email")) .email(object.getString("email"))
.remark(object.getString("slogan")) .remark(object.getString("slogan"))
.token(authToken) .token(authToken)
.source(AuthSource.CODING) .source(AuthSource.CODING)
.build(); .build();
}
/**
* 返回认证url,可自行跳转页面
*
* @return 返回授权地址
*/
@Override
public String authorize() {
return UrlBuilder.fromBaseUrl(source.authorize())
.queryParam("response_type", "code")
.queryParam("client_id", config.getClientId())
.queryParam("redirect_uri", config.getRedirectUri())
.queryParam("scope", "user")
.queryParam("state", getRealState(config.getState()))
.build();
} }
} }
package me.zhyd.oauth.request; package me.zhyd.oauth.request;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse; import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import me.zhyd.oauth.config.AuthConfig; import me.zhyd.oauth.config.AuthConfig;
...@@ -10,8 +9,6 @@ import me.zhyd.oauth.model.AuthCallback; ...@@ -10,8 +9,6 @@ import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthToken; import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser; import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.model.AuthUserGender; import me.zhyd.oauth.model.AuthUserGender;
import me.zhyd.oauth.url.AuthCsdnUrlBuilder;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
/** /**
* CSDN登录 * CSDN登录
...@@ -24,13 +21,12 @@ import me.zhyd.oauth.url.entity.AuthUserInfoEntity; ...@@ -24,13 +21,12 @@ import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
public class AuthCsdnRequest extends AuthDefaultRequest { public class AuthCsdnRequest extends AuthDefaultRequest {
public AuthCsdnRequest(AuthConfig config) { public AuthCsdnRequest(AuthConfig config) {
super(config, AuthSource.CSDN, new AuthCsdnUrlBuilder()); super(config, AuthSource.CSDN);
} }
@Override @Override
protected AuthToken getAccessToken(AuthCallback authCallback) { protected AuthToken getAccessToken(AuthCallback authCallback) {
String accessTokenUrl = this.urlBuilder.getAccessTokenUrl(authCallback.getCode()); HttpResponse response = doPostAuthorizationCode(authCallback.getCode());
HttpResponse response = HttpRequest.post(accessTokenUrl).execute();
JSONObject accessTokenObject = JSONObject.parseObject(response.body()); JSONObject accessTokenObject = JSONObject.parseObject(response.body());
if (accessTokenObject.containsKey("error_code")) { if (accessTokenObject.containsKey("error_code")) {
throw new AuthException("Unable to get token from csdn using code [" + authCallback.getCode() + "]: " + accessTokenObject); throw new AuthException("Unable to get token from csdn using code [" + authCallback.getCode() + "]: " + accessTokenObject);
...@@ -40,22 +36,19 @@ public class AuthCsdnRequest extends AuthDefaultRequest { ...@@ -40,22 +36,19 @@ public class AuthCsdnRequest extends AuthDefaultRequest {
@Override @Override
protected AuthUser getUserInfo(AuthToken authToken) { protected AuthUser getUserInfo(AuthToken authToken) {
String accessToken = authToken.getAccessToken(); HttpResponse response = doGetUserInfo(authToken);
HttpResponse response = HttpRequest.get(this.urlBuilder.getUserInfoUrl(AuthUserInfoEntity.builder()
.accessToken(accessToken)
.build())).execute();
JSONObject object = JSONObject.parseObject(response.body()); JSONObject object = JSONObject.parseObject(response.body());
if (object.containsKey("error_code")) { if (object.containsKey("error_code")) {
throw new AuthException(object.getString("error")); throw new AuthException(object.getString("error"));
} }
return AuthUser.builder() return AuthUser.builder()
.uuid(object.getString("username")) .uuid(object.getString("username"))
.username(object.getString("username")) .username(object.getString("username"))
.remark(object.getString("description")) .remark(object.getString("description"))
.blog(object.getString("website")) .blog(object.getString("website"))
.gender(AuthUserGender.UNKNOWN) .gender(AuthUserGender.UNKNOWN)
.token(authToken) .token(authToken)
.source(AuthSource.CSDN) .source(AuthSource.CSDN)
.build(); .build();
} }
} }
package me.zhyd.oauth.request; package me.zhyd.oauth.request;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import lombok.Data; import lombok.Data;
import me.zhyd.oauth.config.AuthConfig; import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthSource; import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException; import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.*; import me.zhyd.oauth.model.*;
import me.zhyd.oauth.url.AuthDefaultUrlBuilder;
import me.zhyd.oauth.utils.AuthChecker; import me.zhyd.oauth.utils.AuthChecker;
import me.zhyd.oauth.utils.StringUtils;
import me.zhyd.oauth.utils.UrlBuilder;
/** /**
* 默认的request处理类 * 默认的request处理类
* *
* @author yadong.zhang (yadong.zhang0415(a)gmail.com) * @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @author yangkai.shen (https://xkcoding.com)
* @version 1.0 * @version 1.0
* @since 1.8 * @since 1.8
*/ */
...@@ -19,7 +23,6 @@ import me.zhyd.oauth.utils.AuthChecker; ...@@ -19,7 +23,6 @@ import me.zhyd.oauth.utils.AuthChecker;
public abstract class AuthDefaultRequest implements AuthRequest { public abstract class AuthDefaultRequest implements AuthRequest {
protected AuthConfig config; protected AuthConfig config;
protected AuthSource source; protected AuthSource source;
protected AuthDefaultUrlBuilder urlBuilder;
public AuthDefaultRequest(AuthConfig config, AuthSource source) { public AuthDefaultRequest(AuthConfig config, AuthSource source) {
this.config = config; this.config = config;
...@@ -31,12 +34,6 @@ public abstract class AuthDefaultRequest implements AuthRequest { ...@@ -31,12 +34,6 @@ public abstract class AuthDefaultRequest implements AuthRequest {
AuthChecker.checkConfig(config, source); AuthChecker.checkConfig(config, source);
} }
public AuthDefaultRequest(AuthConfig config, AuthSource source, AuthDefaultUrlBuilder urlBuilder) {
this(config, source);
this.urlBuilder = urlBuilder;
this.urlBuilder.setAuthConfig(config);
}
protected abstract AuthToken getAccessToken(AuthCallback authCallback); protected abstract AuthToken getAccessToken(AuthCallback authCallback);
protected abstract AuthUser getUserInfo(AuthToken authToken); protected abstract AuthUser getUserInfo(AuthToken authToken);
...@@ -70,6 +67,100 @@ public abstract class AuthDefaultRequest implements AuthRequest { ...@@ -70,6 +67,100 @@ public abstract class AuthDefaultRequest implements AuthRequest {
*/ */
@Override @Override
public String authorize() { public String authorize() {
return this.urlBuilder.getAuthorizeUrl(); return UrlBuilder.fromBaseUrl(source.authorize())
.queryParam("response_type", "code")
.queryParam("client_id", config.getClientId())
.queryParam("redirect_uri", config.getRedirectUri())
.queryParam("state", getRealState(config.getState()))
.build();
}
/**
* 返回获取accessToken的url
*
* @return 返回获取accessToken的url
*/
protected String accessTokenUrl(String code) {
return UrlBuilder.fromBaseUrl(source.accessToken())
.queryParam("code", code)
.queryParam("client_id", config.getClientId())
.queryParam("client_secret", config.getClientSecret())
.queryParam("grant_type", "authorization_code")
.queryParam("redirect_uri", config.getRedirectUri())
.build();
}
/**
* 返回获取accessToken的url
*
* @return 返回获取accessToken的url
*/
protected String refreshTokenUrl(String refreshToken) {
return UrlBuilder.fromBaseUrl(source.refresh())
.queryParam("client_id", config.getClientId())
.queryParam("client_secret", config.getClientSecret())
.queryParam("refresh_token", refreshToken)
.queryParam("grant_type", "refresh_token")
.queryParam("redirect_uri", config.getRedirectUri())
.build();
}
/**
* 返回获取userInfo的url
*
* @return 返回获取userInfo的url
*/
protected String userInfoUrl(AuthToken authToken) {
return UrlBuilder.fromBaseUrl(source.userInfo()).queryParam("access_token", authToken.getAccessToken()).build();
}
/**
* 获取state,如果为空, 则默认去当前日期的时间戳
*
* @param state 原始的state
* @return 返回不为null的state
*/
protected String getRealState(String state) {
return StringUtils.isEmpty(state) ? String.valueOf(System.currentTimeMillis()) : state;
}
/**
* 通用的 authorizationCode 协议
*
* @param code code码
* @return HttpResponse
*/
protected HttpResponse doPostAuthorizationCode(String code) {
return HttpRequest.post(accessTokenUrl(code)).execute();
}
/**
* 通用的 authorizationCode 协议
*
* @param code code码
* @return HttpResponse
*/
protected HttpResponse doGetAuthorizationCode(String code) {
return HttpRequest.get(accessTokenUrl(code)).execute();
}
/**
* 通用的 用户信息
*
* @param authToken token封装
* @return HttpResponse
*/
protected HttpResponse doPostUserInfo(AuthToken authToken) {
return HttpRequest.post(userInfoUrl(authToken)).execute();
}
/**
* 通用的 用户信息
*
* @param authToken token封装
* @return HttpResponse
*/
protected HttpResponse doGetUserInfo(AuthToken authToken) {
return HttpRequest.get(userInfoUrl(authToken)).execute();
} }
} }
...@@ -12,9 +12,8 @@ import me.zhyd.oauth.model.AuthCallback; ...@@ -12,9 +12,8 @@ import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthToken; import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser; import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.model.AuthUserGender; import me.zhyd.oauth.model.AuthUserGender;
import me.zhyd.oauth.url.AuthDingtalkUrlBuilder;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
import me.zhyd.oauth.utils.GlobalAuthUtil; import me.zhyd.oauth.utils.GlobalAuthUtil;
import me.zhyd.oauth.utils.UrlBuilder;
/** /**
* 钉钉登录 * 钉钉登录
...@@ -26,7 +25,7 @@ import me.zhyd.oauth.utils.GlobalAuthUtil; ...@@ -26,7 +25,7 @@ import me.zhyd.oauth.utils.GlobalAuthUtil;
public class AuthDingTalkRequest extends AuthDefaultRequest { public class AuthDingTalkRequest extends AuthDefaultRequest {
public AuthDingTalkRequest(AuthConfig config) { public AuthDingTalkRequest(AuthConfig config) {
super(config, AuthSource.DINGTALK, new AuthDingtalkUrlBuilder()); super(config, AuthSource.DINGTALK);
} }
@Override @Override
...@@ -37,17 +36,9 @@ public class AuthDingTalkRequest extends AuthDefaultRequest { ...@@ -37,17 +36,9 @@ public class AuthDingTalkRequest extends AuthDefaultRequest {
@Override @Override
protected AuthUser getUserInfo(AuthToken authToken) { protected AuthUser getUserInfo(AuthToken authToken) {
String code = authToken.getAccessCode(); String code = authToken.getAccessCode();
// 根据timestamp, appSecret计算签名值
String timestamp = System.currentTimeMillis() + "";
String urlEncodeSignature = GlobalAuthUtil.generateDingTalkSignature(config.getClientSecret(), timestamp);
JSONObject param = new JSONObject(); JSONObject param = new JSONObject();
param.put("tmp_auth_code", code); param.put("tmp_auth_code", code);
HttpResponse response = HttpRequest.post(this.urlBuilder.getUserInfoUrl(AuthUserInfoEntity.builder() HttpResponse response = HttpRequest.post(userInfoUrl(authToken)).body(param.toJSONString()).execute();
.signature(urlEncodeSignature)
.timestamp(timestamp)
.clientId(config.getClientId())
.build()
)).body(param.toJSONString()).execute();
String userInfo = response.body(); String userInfo = response.body();
JSONObject object = JSON.parseObject(userInfo); JSONObject object = JSON.parseObject(userInfo);
AuthDingTalkErrorCode errorCode = AuthDingTalkErrorCode.getErrorCode(object.getIntValue("errcode")); AuthDingTalkErrorCode errorCode = AuthDingTalkErrorCode.getErrorCode(object.getIntValue("errcode"));
...@@ -56,16 +47,51 @@ public class AuthDingTalkRequest extends AuthDefaultRequest { ...@@ -56,16 +47,51 @@ public class AuthDingTalkRequest extends AuthDefaultRequest {
} }
object = object.getJSONObject("user_info"); object = object.getJSONObject("user_info");
AuthToken token = AuthToken.builder() AuthToken token = AuthToken.builder()
.openId(object.getString("openid")) .openId(object.getString("openid"))
.unionId(object.getString("unionid")) .unionId(object.getString("unionid"))
.build(); .build();
return AuthUser.builder() return AuthUser.builder()
.uuid(object.getString("unionid")) .uuid(object.getString("unionid"))
.nickname(object.getString("nick")) .nickname(object.getString("nick"))
.username(object.getString("nick")) .username(object.getString("nick"))
.gender(AuthUserGender.UNKNOWN) .gender(AuthUserGender.UNKNOWN)
.source(AuthSource.DINGTALK) .source(AuthSource.DINGTALK)
.token(token) .token(token)
.build(); .build();
}
/**
* 返回认证url,可自行跳转页面
*
* @return 返回授权地址
*/
@Override
public String authorize() {
return UrlBuilder.fromBaseUrl(source.authorize())
.queryParam("response_type", "code")
.queryParam("appid", config.getClientId())
.queryParam("scope", "snsapi_login")
.queryParam("redirect_uri", config.getRedirectUri())
.queryParam("state", getRealState(config.getState()))
.build();
}
/**
* 返回获取userInfo的url
*
* @param authToken
* @return 返回获取userInfo的url
*/
@Override
protected String userInfoUrl(AuthToken authToken) {
// 根据timestamp, appSecret计算签名值
String timestamp = System.currentTimeMillis() + "";
String urlEncodeSignature = GlobalAuthUtil.generateDingTalkSignature(config.getClientSecret(), timestamp);
return UrlBuilder.fromBaseUrl(source.userInfo())
.queryParam("signature", urlEncodeSignature)
.queryParam("timestamp", timestamp)
.queryParam("accessKey", config.getClientId())
.build();
} }
} }
...@@ -7,8 +7,7 @@ import me.zhyd.oauth.config.AuthConfig; ...@@ -7,8 +7,7 @@ import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthSource; import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException; import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.*; import me.zhyd.oauth.model.*;
import me.zhyd.oauth.url.AuthDouyinUrlBuilder; import me.zhyd.oauth.utils.UrlBuilder;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
/** /**
...@@ -21,47 +20,39 @@ import me.zhyd.oauth.url.entity.AuthUserInfoEntity; ...@@ -21,47 +20,39 @@ import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
public class AuthDouyinRequest extends AuthDefaultRequest { public class AuthDouyinRequest extends AuthDefaultRequest {
public AuthDouyinRequest(AuthConfig config) { public AuthDouyinRequest(AuthConfig config) {
super(config, AuthSource.DOUYIN, new AuthDouyinUrlBuilder()); super(config, AuthSource.DOUYIN);
} }
@Override @Override
protected AuthToken getAccessToken(AuthCallback authCallback) { protected AuthToken getAccessToken(AuthCallback authCallback) {
String accessTokenUrl = this.urlBuilder.getAccessTokenUrl(authCallback.getCode()); return this.getToken(accessTokenUrl(authCallback.getCode()));
return this.getToken(accessTokenUrl);
} }
@Override @Override
protected AuthUser getUserInfo(AuthToken authToken) { protected AuthUser getUserInfo(AuthToken authToken) {
String accessToken = authToken.getAccessToken(); HttpResponse response = doGetUserInfo(authToken);
String openId = authToken.getOpenId();
String url = this.urlBuilder.getUserInfoUrl(AuthUserInfoEntity.builder()
.accessToken(accessToken)
.openId(openId)
.build());
HttpResponse response = HttpRequest.get(url).execute();
JSONObject object = JSONObject.parseObject(response.body()); JSONObject object = JSONObject.parseObject(response.body());
JSONObject userInfoObject = this.checkResponse(object); JSONObject userInfoObject = this.checkResponse(object);
return AuthUser.builder() return AuthUser.builder()
.uuid(userInfoObject.getString("union_id")) .uuid(userInfoObject.getString("union_id"))
.username(userInfoObject.getString("nickname")) .username(userInfoObject.getString("nickname"))
.nickname(userInfoObject.getString("nickname")) .nickname(userInfoObject.getString("nickname"))
.avatar(userInfoObject.getString("avatar")) .avatar(userInfoObject.getString("avatar"))
.remark(userInfoObject.getString("description")) .remark(userInfoObject.getString("description"))
.gender(AuthUserGender.UNKNOWN) .gender(AuthUserGender.UNKNOWN)
.token(authToken) .token(authToken)
.source(AuthSource.DOUYIN) .source(AuthSource.DOUYIN)
.build(); .build();
} }
@Override @Override
public AuthResponse refresh(AuthToken oldToken) { public AuthResponse refresh(AuthToken oldToken) {
String refreshTokenUrl = this.urlBuilder.getRefreshUrl(oldToken.getRefreshToken());
return AuthResponse.builder() return AuthResponse.builder()
.code(AuthResponseStatus.SUCCESS.getCode()) .code(AuthResponseStatus.SUCCESS.getCode())
.data(this.getToken(refreshTokenUrl)) .data(refreshTokenUrl(oldToken.getRefreshToken()))
.build(); .build();
} }
/** /**
...@@ -93,11 +84,72 @@ public class AuthDouyinRequest extends AuthDefaultRequest { ...@@ -93,11 +84,72 @@ public class AuthDouyinRequest extends AuthDefaultRequest {
JSONObject accessTokenObject = this.checkResponse(object); JSONObject accessTokenObject = this.checkResponse(object);
return AuthToken.builder() return AuthToken.builder()
.accessToken(accessTokenObject.getString("access_token")) .accessToken(accessTokenObject.getString("access_token"))
.openId(accessTokenObject.getString("open_id")) .openId(accessTokenObject.getString("open_id"))
.expireIn(accessTokenObject.getIntValue("expires_in")) .expireIn(accessTokenObject.getIntValue("expires_in"))
.refreshToken(accessTokenObject.getString("refresh_token")) .refreshToken(accessTokenObject.getString("refresh_token"))
.scope(accessTokenObject.getString("scope")) .scope(accessTokenObject.getString("scope"))
.build(); .build();
}
/**
* 返回认证url,可自行跳转页面
*
* @return 返回授权地址
*/
@Override
public String authorize() {
return UrlBuilder.fromBaseUrl(source.authorize())
.queryParam("response_type", "code")
.queryParam("client_key", config.getClientId())
.queryParam("redirect_uri", config.getRedirectUri())
.queryParam("state", getRealState(config.getState()))
.queryParam("scope", "user_info")
.build();
}
/**
* 返回获取accessToken的url
*
* @param code
* @return 返回获取accessToken的url
*/
@Override
protected String accessTokenUrl(String code) {
return UrlBuilder.fromBaseUrl(source.accessToken())
.queryParam("code", code)
.queryParam("client_key", config.getClientId())
.queryParam("client_secret", config.getClientSecret())
.queryParam("grant_type", "authorization_code")
.build();
}
/**
* 返回获取userInfo的url
*
* @param authToken
* @return 返回获取userInfo的url
*/
@Override
protected String userInfoUrl(AuthToken authToken) {
return UrlBuilder.fromBaseUrl(source.userInfo())
.queryParam("access_token", authToken.getAccessToken())
.queryParam("open_id", authToken.getOpenId())
.build();
}
/**
* 返回获取accessToken的url
*
* @param refreshToken
* @return 返回获取accessToken的url
*/
@Override
protected String refreshTokenUrl(String refreshToken) {
return UrlBuilder.fromBaseUrl(source.refresh())
.queryParam("client_key", config.getClientId())
.queryParam("refresh_token", refreshToken)
.queryParam("grant_type", "refresh_token")
.build();
} }
} }
package me.zhyd.oauth.request; package me.zhyd.oauth.request;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse; import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import me.zhyd.oauth.config.AuthConfig; import me.zhyd.oauth.config.AuthConfig;
...@@ -10,8 +9,7 @@ import me.zhyd.oauth.model.AuthCallback; ...@@ -10,8 +9,7 @@ import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthToken; import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser; import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.model.AuthUserGender; import me.zhyd.oauth.model.AuthUserGender;
import me.zhyd.oauth.url.AuthFacebookUrlBuilder; import me.zhyd.oauth.utils.UrlBuilder;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
/** /**
* Facebook登录 * Facebook登录
...@@ -23,13 +21,12 @@ import me.zhyd.oauth.url.entity.AuthUserInfoEntity; ...@@ -23,13 +21,12 @@ import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
public class AuthFacebookRequest extends AuthDefaultRequest { public class AuthFacebookRequest extends AuthDefaultRequest {
public AuthFacebookRequest(AuthConfig config) { public AuthFacebookRequest(AuthConfig config) {
super(config, AuthSource.FACEBOOK, new AuthFacebookUrlBuilder()); super(config, AuthSource.FACEBOOK);
} }
@Override @Override
protected AuthToken getAccessToken(AuthCallback authCallback) { protected AuthToken getAccessToken(AuthCallback authCallback) {
String accessTokenUrl = this.urlBuilder.getAccessTokenUrl(authCallback.getCode()); HttpResponse response = doPostAuthorizationCode(authCallback.getCode());
HttpResponse response = HttpRequest.post(accessTokenUrl).execute();
JSONObject accessTokenObject = JSONObject.parseObject(response.body()); JSONObject accessTokenObject = JSONObject.parseObject(response.body());
if (accessTokenObject.containsKey("error")) { if (accessTokenObject.containsKey("error")) {
...@@ -37,18 +34,15 @@ public class AuthFacebookRequest extends AuthDefaultRequest { ...@@ -37,18 +34,15 @@ public class AuthFacebookRequest extends AuthDefaultRequest {
} }
return AuthToken.builder() return AuthToken.builder()
.accessToken(accessTokenObject.getString("access_token")) .accessToken(accessTokenObject.getString("access_token"))
.expireIn(accessTokenObject.getIntValue("expires_in")) .expireIn(accessTokenObject.getIntValue("expires_in"))
.tokenType(accessTokenObject.getString("token_type")) .tokenType(accessTokenObject.getString("token_type"))
.build(); .build();
} }
@Override @Override
protected AuthUser getUserInfo(AuthToken authToken) { protected AuthUser getUserInfo(AuthToken authToken) {
String accessToken = authToken.getAccessToken(); HttpResponse response = doGetUserInfo(authToken);
HttpResponse response = HttpRequest.get(this.urlBuilder.getUserInfoUrl(AuthUserInfoEntity.builder()
.accessToken(accessToken)
.build())).execute();
String userInfo = response.body(); String userInfo = response.body();
JSONObject object = JSONObject.parseObject(userInfo); JSONObject object = JSONObject.parseObject(userInfo);
if (object.containsKey("error")) { if (object.containsKey("error")) {
...@@ -63,15 +57,29 @@ public class AuthFacebookRequest extends AuthDefaultRequest { ...@@ -63,15 +57,29 @@ public class AuthFacebookRequest extends AuthDefaultRequest {
} }
} }
return AuthUser.builder() return AuthUser.builder()
.uuid(object.getString("id")) .uuid(object.getString("id"))
.username(object.getString("name")) .username(object.getString("name"))
.nickname(object.getString("name")) .nickname(object.getString("name"))
.avatar(picture) .avatar(picture)
.location(object.getString("locale")) .location(object.getString("locale"))
.email(object.getString("email")) .email(object.getString("email"))
.gender(AuthUserGender.getRealGender(object.getString("gender"))) .gender(AuthUserGender.getRealGender(object.getString("gender")))
.token(authToken) .token(authToken)
.source(AuthSource.FACEBOOK) .source(AuthSource.FACEBOOK)
.build(); .build();
}
/**
* 返回获取userInfo的url
*
* @param authToken
* @return 返回获取userInfo的url
*/
@Override
protected String userInfoUrl(AuthToken authToken) {
return UrlBuilder.fromBaseUrl(source.userInfo())
.queryParam("access_token", authToken.getAccessToken())
.queryParam("fields", "id,name,birthday,gender,hometown,email,devices,picture.width(400)")
.build();
} }
} }
package me.zhyd.oauth.request; package me.zhyd.oauth.request;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse; import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import me.zhyd.oauth.config.AuthConfig; import me.zhyd.oauth.config.AuthConfig;
...@@ -10,8 +9,6 @@ import me.zhyd.oauth.model.AuthCallback; ...@@ -10,8 +9,6 @@ import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthToken; import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser; import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.model.AuthUserGender; import me.zhyd.oauth.model.AuthUserGender;
import me.zhyd.oauth.url.AuthGiteeUrlBuilder;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
/** /**
* Gitee登录 * Gitee登录
...@@ -23,13 +20,12 @@ import me.zhyd.oauth.url.entity.AuthUserInfoEntity; ...@@ -23,13 +20,12 @@ import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
public class AuthGiteeRequest extends AuthDefaultRequest { public class AuthGiteeRequest extends AuthDefaultRequest {
public AuthGiteeRequest(AuthConfig config) { public AuthGiteeRequest(AuthConfig config) {
super(config, AuthSource.GITEE, new AuthGiteeUrlBuilder()); super(config, AuthSource.GITEE);
} }
@Override @Override
protected AuthToken getAccessToken(AuthCallback authCallback) { protected AuthToken getAccessToken(AuthCallback authCallback) {
String accessTokenUrl = this.urlBuilder.getAccessTokenUrl(authCallback.getCode()); HttpResponse response = doPostAuthorizationCode(authCallback.getCode());
HttpResponse response = HttpRequest.post(accessTokenUrl).execute();
JSONObject accessTokenObject = JSONObject.parseObject(response.body()); JSONObject accessTokenObject = JSONObject.parseObject(response.body());
if (accessTokenObject.containsKey("error")) { if (accessTokenObject.containsKey("error")) {
throw new AuthException("Unable to get token from gitee using code [" + authCallback.getCode() + "]: " + accessTokenObject); throw new AuthException("Unable to get token from gitee using code [" + authCallback.getCode() + "]: " + accessTokenObject);
...@@ -39,25 +35,22 @@ public class AuthGiteeRequest extends AuthDefaultRequest { ...@@ -39,25 +35,22 @@ public class AuthGiteeRequest extends AuthDefaultRequest {
@Override @Override
protected AuthUser getUserInfo(AuthToken authToken) { protected AuthUser getUserInfo(AuthToken authToken) {
String accessToken = authToken.getAccessToken(); HttpResponse response = doGetUserInfo(authToken);
HttpResponse response = HttpRequest.get(this.urlBuilder.getUserInfoUrl(AuthUserInfoEntity.builder()
.accessToken(accessToken)
.build())).execute();
String userInfo = response.body(); String userInfo = response.body();
JSONObject object = JSONObject.parseObject(userInfo); JSONObject object = JSONObject.parseObject(userInfo);
return AuthUser.builder() return AuthUser.builder()
.uuid(object.getString("id")) .uuid(object.getString("id"))
.username(object.getString("login")) .username(object.getString("login"))
.avatar(object.getString("avatar_url")) .avatar(object.getString("avatar_url"))
.blog(object.getString("blog")) .blog(object.getString("blog"))
.nickname(object.getString("name")) .nickname(object.getString("name"))
.company(object.getString("company")) .company(object.getString("company"))
.location(object.getString("address")) .location(object.getString("address"))
.email(object.getString("email")) .email(object.getString("email"))
.remark(object.getString("bio")) .remark(object.getString("bio"))
.gender(AuthUserGender.UNKNOWN) .gender(AuthUserGender.UNKNOWN)
.token(authToken) .token(authToken)
.source(AuthSource.GITEE) .source(AuthSource.GITEE)
.build(); .build();
} }
} }
package me.zhyd.oauth.request; package me.zhyd.oauth.request;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse; import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import me.zhyd.oauth.config.AuthConfig; import me.zhyd.oauth.config.AuthConfig;
...@@ -10,8 +9,6 @@ import me.zhyd.oauth.model.AuthCallback; ...@@ -10,8 +9,6 @@ import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthToken; import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser; import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.model.AuthUserGender; import me.zhyd.oauth.model.AuthUserGender;
import me.zhyd.oauth.url.AuthGithubUrlBuilder;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
import me.zhyd.oauth.utils.GlobalAuthUtil; import me.zhyd.oauth.utils.GlobalAuthUtil;
import java.util.Map; import java.util.Map;
...@@ -26,13 +23,12 @@ import java.util.Map; ...@@ -26,13 +23,12 @@ import java.util.Map;
public class AuthGithubRequest extends AuthDefaultRequest { public class AuthGithubRequest extends AuthDefaultRequest {
public AuthGithubRequest(AuthConfig config) { public AuthGithubRequest(AuthConfig config) {
super(config, AuthSource.GITHUB, new AuthGithubUrlBuilder()); super(config, AuthSource.GITHUB);
} }
@Override @Override
protected AuthToken getAccessToken(AuthCallback authCallback) { protected AuthToken getAccessToken(AuthCallback authCallback) {
String accessTokenUrl = this.urlBuilder.getAccessTokenUrl(authCallback.getCode()); HttpResponse response = doPostAuthorizationCode(authCallback.getCode());
HttpResponse response = HttpRequest.post(accessTokenUrl).execute();
Map<String, String> res = GlobalAuthUtil.parseStringToMap(response.body()); Map<String, String> res = GlobalAuthUtil.parseStringToMap(response.body());
if (res.containsKey("error")) { if (res.containsKey("error")) {
throw new AuthException(res.get("error") + ":" + res.get("error_description")); throw new AuthException(res.get("error") + ":" + res.get("error_description"));
...@@ -42,25 +38,22 @@ public class AuthGithubRequest extends AuthDefaultRequest { ...@@ -42,25 +38,22 @@ public class AuthGithubRequest extends AuthDefaultRequest {
@Override @Override
protected AuthUser getUserInfo(AuthToken authToken) { protected AuthUser getUserInfo(AuthToken authToken) {
String accessToken = authToken.getAccessToken(); HttpResponse response = doGetUserInfo(authToken);
HttpResponse response = HttpRequest.get(this.urlBuilder.getUserInfoUrl(AuthUserInfoEntity.builder()
.accessToken(accessToken)
.build())).execute();
String userInfo = response.body(); String userInfo = response.body();
JSONObject object = JSONObject.parseObject(userInfo); JSONObject object = JSONObject.parseObject(userInfo);
return AuthUser.builder() return AuthUser.builder()
.uuid(object.getString("id")) .uuid(object.getString("id"))
.username(object.getString("login")) .username(object.getString("login"))
.avatar(object.getString("avatar_url")) .avatar(object.getString("avatar_url"))
.blog(object.getString("blog")) .blog(object.getString("blog"))
.nickname(object.getString("name")) .nickname(object.getString("name"))
.company(object.getString("company")) .company(object.getString("company"))
.location(object.getString("location")) .location(object.getString("location"))
.email(object.getString("email")) .email(object.getString("email"))
.remark(object.getString("bio")) .remark(object.getString("bio"))
.gender(AuthUserGender.UNKNOWN) .gender(AuthUserGender.UNKNOWN)
.token(authToken) .token(authToken)
.source(AuthSource.GITHUB) .source(AuthSource.GITHUB)
.build(); .build();
} }
} }
package me.zhyd.oauth.request; package me.zhyd.oauth.request;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse; import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import me.zhyd.oauth.config.AuthConfig; import me.zhyd.oauth.config.AuthConfig;
...@@ -10,8 +9,7 @@ import me.zhyd.oauth.model.AuthCallback; ...@@ -10,8 +9,7 @@ import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthToken; import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser; import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.model.AuthUserGender; import me.zhyd.oauth.model.AuthUserGender;
import me.zhyd.oauth.url.AuthGoogleUrlBuilder; import me.zhyd.oauth.utils.UrlBuilder;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
/** /**
* Google登录 * Google登录
...@@ -23,47 +21,70 @@ import me.zhyd.oauth.url.entity.AuthUserInfoEntity; ...@@ -23,47 +21,70 @@ import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
public class AuthGoogleRequest extends AuthDefaultRequest { public class AuthGoogleRequest extends AuthDefaultRequest {
public AuthGoogleRequest(AuthConfig config) { public AuthGoogleRequest(AuthConfig config) {
super(config, AuthSource.GOOGLE, new AuthGoogleUrlBuilder()); super(config, AuthSource.GOOGLE);
} }
@Override @Override
protected AuthToken getAccessToken(AuthCallback authCallback) { protected AuthToken getAccessToken(AuthCallback authCallback) {
String accessTokenUrl = this.urlBuilder.getAccessTokenUrl(authCallback.getCode()); HttpResponse response = doPostAuthorizationCode(authCallback.getCode());
HttpResponse response = HttpRequest.post(accessTokenUrl).execute();
JSONObject accessTokenObject = JSONObject.parseObject(response.body()); JSONObject accessTokenObject = JSONObject.parseObject(response.body());
if (accessTokenObject.containsKey("error") || accessTokenObject.containsKey("error_description")) { if (accessTokenObject.containsKey("error") || accessTokenObject.containsKey("error_description")) {
throw new AuthException("get google access_token has error:[" + accessTokenObject.getString("error") + "], error_description:[" + accessTokenObject throw new AuthException("get google access_token has error:[" + accessTokenObject.getString("error") + "], error_description:[" + accessTokenObject
.getString("error_description") + "]"); .getString("error_description") + "]");
} }
return AuthToken.builder() return AuthToken.builder()
.accessToken(accessTokenObject.getString("access_token")) .accessToken(accessTokenObject.getString("access_token"))
.expireIn(accessTokenObject.getIntValue("expires_in")) .expireIn(accessTokenObject.getIntValue("expires_in"))
.scope(accessTokenObject.getString("scope")) .scope(accessTokenObject.getString("scope"))
.tokenType(accessTokenObject.getString("token_type")) .tokenType(accessTokenObject.getString("token_type"))
.idToken(accessTokenObject.getString("id_token")) .idToken(accessTokenObject.getString("id_token"))
.build(); .build();
} }
@Override @Override
protected AuthUser getUserInfo(AuthToken authToken) { protected AuthUser getUserInfo(AuthToken authToken) {
String accessToken = authToken.getIdToken(); HttpResponse response = doGetUserInfo(authToken);
HttpResponse response = HttpRequest.get(this.urlBuilder.getUserInfoUrl(AuthUserInfoEntity.builder()
.accessToken(accessToken)
.build())).execute();
String userInfo = response.body(); String userInfo = response.body();
JSONObject object = JSONObject.parseObject(userInfo); JSONObject object = JSONObject.parseObject(userInfo);
return AuthUser.builder() return AuthUser.builder()
.uuid(object.getString("sub")) .uuid(object.getString("sub"))
.username(object.getString("name")) .username(object.getString("name"))
.avatar(object.getString("picture")) .avatar(object.getString("picture"))
.nickname(object.getString("name")) .nickname(object.getString("name"))
.location(object.getString("locale")) .location(object.getString("locale"))
.email(object.getString("email")) .email(object.getString("email"))
.gender(AuthUserGender.UNKNOWN) .gender(AuthUserGender.UNKNOWN)
.token(authToken) .token(authToken)
.source(AuthSource.GOOGLE) .source(AuthSource.GOOGLE)
.build(); .build();
}
/**
* 返回认证url,可自行跳转页面
*
* @return 返回授权地址
*/
@Override
public String authorize() {
return UrlBuilder.fromBaseUrl(source.authorize())
.queryParam("response_type", "code")
.queryParam("client_id", config.getClientId())
.queryParam("scope", "openid%20email%20profile")
.queryParam("redirect_uri", config.getRedirectUri())
.queryParam("state", getRealState(config.getState()))
.build();
}
/**
* 返回获取userInfo的url
*
* @param authToken
* @return 返回获取userInfo的url
*/
@Override
protected String userInfoUrl(AuthToken authToken) {
return UrlBuilder.fromBaseUrl(source.userInfo()).queryParam("id_token", authToken.getAccessToken()).build();
} }
} }
...@@ -8,9 +8,8 @@ import me.zhyd.oauth.config.AuthConfig; ...@@ -8,9 +8,8 @@ import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthSource; import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException; import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.*; import me.zhyd.oauth.model.*;
import me.zhyd.oauth.url.AuthLinkedinUrlBuilder;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
import me.zhyd.oauth.utils.StringUtils; import me.zhyd.oauth.utils.StringUtils;
import me.zhyd.oauth.utils.UrlBuilder;
/** /**
...@@ -23,23 +22,22 @@ import me.zhyd.oauth.utils.StringUtils; ...@@ -23,23 +22,22 @@ import me.zhyd.oauth.utils.StringUtils;
public class AuthLinkedinRequest extends AuthDefaultRequest { public class AuthLinkedinRequest extends AuthDefaultRequest {
public AuthLinkedinRequest(AuthConfig config) { public AuthLinkedinRequest(AuthConfig config) {
super(config, AuthSource.LINKEDIN, new AuthLinkedinUrlBuilder()); super(config, AuthSource.LINKEDIN);
} }
@Override @Override
protected AuthToken getAccessToken(AuthCallback authCallback) { protected AuthToken getAccessToken(AuthCallback authCallback) {
String accessTokenUrl = this.urlBuilder.getAccessTokenUrl(authCallback.getCode()); return this.getToken(accessTokenUrl(authCallback.getCode()));
return this.getToken(accessTokenUrl);
} }
@Override @Override
protected AuthUser getUserInfo(AuthToken authToken) { protected AuthUser getUserInfo(AuthToken authToken) {
String accessToken = authToken.getAccessToken(); String accessToken = authToken.getAccessToken();
HttpResponse response = HttpRequest.get(this.urlBuilder.getUserInfoUrl(AuthUserInfoEntity.builder().build())) HttpResponse response = HttpRequest.get(userInfoUrl(authToken))
.header("Host", "api.linkedin.com") .header("Host", "api.linkedin.com")
.header("Connection", "Keep-Alive") .header("Connection", "Keep-Alive")
.header("Authorization", "Bearer " + accessToken) .header("Authorization", "Bearer " + accessToken)
.execute(); .execute();
JSONObject userInfoObject = JSONObject.parseObject(response.body()); JSONObject userInfoObject = JSONObject.parseObject(response.body());
this.checkResponse(userInfoObject); this.checkResponse(userInfoObject);
...@@ -65,7 +63,7 @@ public class AuthLinkedinRequest extends AuthDefaultRequest { ...@@ -65,7 +63,7 @@ public class AuthLinkedinRequest extends AuthDefaultRequest {
JSONObject profilePictureObject = userInfoObject.getJSONObject("profilePicture"); JSONObject profilePictureObject = userInfoObject.getJSONObject("profilePicture");
if (profilePictureObject.containsKey("displayImage~")) { if (profilePictureObject.containsKey("displayImage~")) {
JSONArray displayImageElements = profilePictureObject.getJSONObject("displayImage~") JSONArray displayImageElements = profilePictureObject.getJSONObject("displayImage~")
.getJSONArray("elements"); .getJSONArray("elements");
if (null != displayImageElements && displayImageElements.size() > 0) { if (null != displayImageElements && displayImageElements.size() > 0) {
JSONObject largestImageObj = displayImageElements.getJSONObject(displayImageElements.size() - 1); JSONObject largestImageObj = displayImageElements.getJSONObject(displayImageElements.size() - 1);
avatar = largestImageObj.getJSONArray("identifiers").getJSONObject(0).getString("identifier"); avatar = largestImageObj.getJSONArray("identifiers").getJSONObject(0).getString("identifier");
...@@ -75,31 +73,31 @@ public class AuthLinkedinRequest extends AuthDefaultRequest { ...@@ -75,31 +73,31 @@ public class AuthLinkedinRequest extends AuthDefaultRequest {
// 获取用户邮箱地址 // 获取用户邮箱地址
String email = this.getUserEmail(accessToken); String email = this.getUserEmail(accessToken);
return AuthUser.builder() return AuthUser.builder()
.uuid(userInfoObject.getString("id")) .uuid(userInfoObject.getString("id"))
.username(userName) .username(userName)
.nickname(userName) .nickname(userName)
.avatar(avatar) .avatar(avatar)
.email(email) .email(email)
.token(authToken) .token(authToken)
.gender(AuthUserGender.UNKNOWN) .gender(AuthUserGender.UNKNOWN)
.source(AuthSource.LINKEDIN) .source(AuthSource.LINKEDIN)
.build(); .build();
} }
private String getUserEmail(String accessToken) { private String getUserEmail(String accessToken) {
String email = null; String email = null;
HttpResponse emailResponse = HttpRequest.get("https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))") HttpResponse emailResponse = HttpRequest.get("https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))")
.header("Host", "api.linkedin.com") .header("Host", "api.linkedin.com")
.header("Connection", "Keep-Alive") .header("Connection", "Keep-Alive")
.header("Authorization", "Bearer " + accessToken) .header("Authorization", "Bearer " + accessToken)
.execute(); .execute();
System.out.println(emailResponse.body()); System.out.println(emailResponse.body());
JSONObject emailObj = JSONObject.parseObject(emailResponse.body()); JSONObject emailObj = JSONObject.parseObject(emailResponse.body());
if (emailObj.containsKey("elements")) { if (emailObj.containsKey("elements")) {
email = emailObj.getJSONArray("elements") email = emailObj.getJSONArray("elements")
.getJSONObject(0) .getJSONObject(0)
.getJSONObject("handle~") .getJSONObject("handle~")
.getString("emailAddress"); .getString("emailAddress");
} }
return email; return email;
} }
...@@ -115,14 +113,15 @@ public class AuthLinkedinRequest extends AuthDefaultRequest { ...@@ -115,14 +113,15 @@ public class AuthLinkedinRequest extends AuthDefaultRequest {
@Override @Override
public AuthResponse refresh(AuthToken oldToken) { public AuthResponse refresh(AuthToken oldToken) {
if (StringUtils.isEmpty(oldToken.getRefreshToken())) { String refreshToken = oldToken.getRefreshToken();
if (StringUtils.isEmpty(refreshToken)) {
throw new AuthException(AuthResponseStatus.UNSUPPORTED); throw new AuthException(AuthResponseStatus.UNSUPPORTED);
} }
String refreshTokenUrl = this.urlBuilder.getRefreshUrl(oldToken.getRefreshToken()); String refreshTokenUrl = refreshTokenUrl(refreshToken);
return AuthResponse.builder() return AuthResponse.builder()
.code(AuthResponseStatus.SUCCESS.getCode()) .code(AuthResponseStatus.SUCCESS.getCode())
.data(this.getToken(refreshTokenUrl)) .data(this.getToken(refreshTokenUrl))
.build(); .build();
} }
private void checkResponse(JSONObject userInfoObject) { private void checkResponse(JSONObject userInfoObject) {
...@@ -139,18 +138,47 @@ public class AuthLinkedinRequest extends AuthDefaultRequest { ...@@ -139,18 +138,47 @@ public class AuthLinkedinRequest extends AuthDefaultRequest {
*/ */
private AuthToken getToken(String accessTokenUrl) { private AuthToken getToken(String accessTokenUrl) {
HttpResponse response = HttpRequest.post(accessTokenUrl) HttpResponse response = HttpRequest.post(accessTokenUrl)
.header("Host", "www.linkedin.com") .header("Host", "www.linkedin.com")
.header("Content-Type", "application/x-www-form-urlencoded") .header("Content-Type", "application/x-www-form-urlencoded")
.execute(); .execute();
String accessTokenStr = response.body(); String accessTokenStr = response.body();
JSONObject accessTokenObject = JSONObject.parseObject(accessTokenStr); JSONObject accessTokenObject = JSONObject.parseObject(accessTokenStr);
this.checkResponse(accessTokenObject); this.checkResponse(accessTokenObject);
return AuthToken.builder() return AuthToken.builder()
.accessToken(accessTokenObject.getString("access_token")) .accessToken(accessTokenObject.getString("access_token"))
.expireIn(accessTokenObject.getIntValue("expires_in")) .expireIn(accessTokenObject.getIntValue("expires_in"))
.refreshToken(accessTokenObject.getString("refresh_token")) .refreshToken(accessTokenObject.getString("refresh_token"))
.build(); .build();
}
/**
* 返回认证url,可自行跳转页面
*
* @return 返回授权地址
*/
@Override
public String authorize() {
return UrlBuilder.fromBaseUrl(source.authorize())
.queryParam("response_type", "code")
.queryParam("client_id", config.getClientId())
.queryParam("redirect_uri", config.getRedirectUri())
.queryParam("state", getRealState(config.getState()))
.queryParam("scope", "r_liteprofile%20r_emailaddress%20w_member_social")
.build();
}
/**
* 返回获取userInfo的url
*
* @param authToken
* @return 返回获取userInfo的url
*/
@Override
protected String userInfoUrl(AuthToken authToken) {
return UrlBuilder.fromBaseUrl(source.userInfo())
.queryParam("projection", "(id,firstName,lastName,profilePicture(displayImage~:playableStreams))")
.build();
} }
} }
...@@ -9,8 +9,7 @@ import me.zhyd.oauth.config.AuthConfig; ...@@ -9,8 +9,7 @@ import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthSource; import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException; import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.*; import me.zhyd.oauth.model.*;
import me.zhyd.oauth.url.AuthMiUrlBuilder; import me.zhyd.oauth.utils.UrlBuilder;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
import java.text.MessageFormat; import java.text.MessageFormat;
...@@ -26,13 +25,12 @@ public class AuthMiRequest extends AuthDefaultRequest { ...@@ -26,13 +25,12 @@ public class AuthMiRequest extends AuthDefaultRequest {
private static final String PREFIX = "&&&START&&&"; private static final String PREFIX = "&&&START&&&";
public AuthMiRequest(AuthConfig config) { public AuthMiRequest(AuthConfig config) {
super(config, AuthSource.MI, new AuthMiUrlBuilder()); super(config, AuthSource.MI);
} }
@Override @Override
protected AuthToken getAccessToken(AuthCallback authCallback) { protected AuthToken getAccessToken(AuthCallback authCallback) {
String accessTokenUrl = this.urlBuilder.getAccessTokenUrl(authCallback.getCode()); return getToken(accessTokenUrl(authCallback.getCode()));
return getToken(accessTokenUrl);
} }
private AuthToken getToken(String accessTokenUrl) { private AuthToken getToken(String accessTokenUrl) {
...@@ -45,25 +43,21 @@ public class AuthMiRequest extends AuthDefaultRequest { ...@@ -45,25 +43,21 @@ public class AuthMiRequest extends AuthDefaultRequest {
} }
return AuthToken.builder() return AuthToken.builder()
.accessToken(accessTokenObject.getString("access_token")) .accessToken(accessTokenObject.getString("access_token"))
.expireIn(accessTokenObject.getIntValue("expires_in")) .expireIn(accessTokenObject.getIntValue("expires_in"))
.scope(accessTokenObject.getString("scope")) .scope(accessTokenObject.getString("scope"))
.tokenType(accessTokenObject.getString("token_type")) .tokenType(accessTokenObject.getString("token_type"))
.refreshToken(accessTokenObject.getString("refresh_token")) .refreshToken(accessTokenObject.getString("refresh_token"))
.openId(accessTokenObject.getString("openId")) .openId(accessTokenObject.getString("openId"))
.macAlgorithm(accessTokenObject.getString("mac_algorithm")) .macAlgorithm(accessTokenObject.getString("mac_algorithm"))
.macKey(accessTokenObject.getString("mac_key")) .macKey(accessTokenObject.getString("mac_key"))
.build(); .build();
} }
@Override @Override
protected AuthUser getUserInfo(AuthToken authToken) { protected AuthUser getUserInfo(AuthToken authToken) {
// 获取用户信息 // 获取用户信息
HttpResponse userResponse = HttpRequest.get(this.urlBuilder.getUserInfoUrl(AuthUserInfoEntity.builder() HttpResponse userResponse = doGetUserInfo(authToken);
.clientId(config.getClientId())
.accessToken(authToken.getAccessToken())
.build()))
.execute();
JSONObject userProfile = JSONObject.parseObject(userResponse.body()); JSONObject userProfile = JSONObject.parseObject(userResponse.body());
if ("error".equalsIgnoreCase(userProfile.getString("result"))) { if ("error".equalsIgnoreCase(userProfile.getString("result"))) {
...@@ -73,19 +67,19 @@ public class AuthMiRequest extends AuthDefaultRequest { ...@@ -73,19 +67,19 @@ public class AuthMiRequest extends AuthDefaultRequest {
JSONObject user = userProfile.getJSONObject("data"); JSONObject user = userProfile.getJSONObject("data");
AuthUser authUser = AuthUser.builder() AuthUser authUser = AuthUser.builder()
.uuid(authToken.getOpenId()) .uuid(authToken.getOpenId())
.username(user.getString("miliaoNick")) .username(user.getString("miliaoNick"))
.nickname(user.getString("miliaoNick")) .nickname(user.getString("miliaoNick"))
.avatar(user.getString("miliaoIcon")) .avatar(user.getString("miliaoIcon"))
.email(user.getString("mail")) .email(user.getString("mail"))
.gender(AuthUserGender.UNKNOWN) .gender(AuthUserGender.UNKNOWN)
.token(authToken) .token(authToken)
.source(AuthSource.MI) .source(AuthSource.MI)
.build(); .build();
// 获取用户邮箱手机号等信息 // 获取用户邮箱手机号等信息
String emailPhoneUrl = MessageFormat.format("{0}?clientId={1}&token={2}", "https://open.account.xiaomi.com/user/phoneAndEmail", config String emailPhoneUrl = MessageFormat.format("{0}?clientId={1}&token={2}", "https://open.account.xiaomi.com/user/phoneAndEmail", config
.getClientId(), authToken.getAccessToken()); .getClientId(), authToken.getAccessToken());
HttpResponse emailResponse = HttpRequest.get(emailPhoneUrl).execute(); HttpResponse emailResponse = HttpRequest.get(emailPhoneUrl).execute();
JSONObject userEmailPhone = JSONObject.parseObject(emailResponse.body()); JSONObject userEmailPhone = JSONObject.parseObject(emailResponse.body());
...@@ -107,8 +101,40 @@ public class AuthMiRequest extends AuthDefaultRequest { ...@@ -107,8 +101,40 @@ public class AuthMiRequest extends AuthDefaultRequest {
*/ */
@Override @Override
public AuthResponse refresh(AuthToken authToken) { public AuthResponse refresh(AuthToken authToken) {
String miRefreshUrl = this.urlBuilder.getRefreshUrl(authToken.getRefreshToken()); return AuthResponse.builder()
.code(AuthResponseStatus.SUCCESS.getCode())
.data(getToken(refreshTokenUrl(authToken.getRefreshToken())))
.build();
}
return AuthResponse.builder().code(AuthResponseStatus.SUCCESS.getCode()).data(getToken(miRefreshUrl)).build(); /**
* 返回认证url,可自行跳转页面
*
* @return 返回授权地址
*/
@Override
public String authorize() {
return UrlBuilder.fromBaseUrl(source.authorize())
.queryParam("response_type", "code")
.queryParam("client_id", config.getClientId())
.queryParam("redirect_uri", config.getRedirectUri())
.queryParam("state", getRealState(config.getState()))
.queryParam("scope", "user/profile%20user/openIdV2%20user/phoneAndEmail")
.queryParam("skip_confirm", "false")
.build();
}
/**
* 返回获取userInfo的url
*
* @param authToken
* @return 返回获取userInfo的url
*/
@Override
protected String userInfoUrl(AuthToken authToken) {
return UrlBuilder.fromBaseUrl(source.userInfo())
.queryParam("clientId", config.getClientId())
.queryParam("token", authToken.getAccessToken())
.build();
} }
} }
...@@ -8,8 +8,7 @@ import me.zhyd.oauth.config.AuthConfig; ...@@ -8,8 +8,7 @@ import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthSource; import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException; import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.*; import me.zhyd.oauth.model.*;
import me.zhyd.oauth.url.AuthMicrosoftUrlBuilder; import me.zhyd.oauth.utils.UrlBuilder;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
...@@ -23,14 +22,12 @@ import java.util.Map; ...@@ -23,14 +22,12 @@ import java.util.Map;
*/ */
public class AuthMicrosoftRequest extends AuthDefaultRequest { public class AuthMicrosoftRequest extends AuthDefaultRequest {
public AuthMicrosoftRequest(AuthConfig config) { public AuthMicrosoftRequest(AuthConfig config) {
super(config, AuthSource.MICROSOFT, new AuthMicrosoftUrlBuilder()); super(config, AuthSource.MICROSOFT);
} }
@Override @Override
protected AuthToken getAccessToken(AuthCallback authCallback) { protected AuthToken getAccessToken(AuthCallback authCallback) {
String accessTokenUrl = this.urlBuilder.getAccessTokenUrl(authCallback.getCode()); return getToken(accessTokenUrl(authCallback.getCode()));
return getToken(accessTokenUrl);
} }
/** /**
...@@ -43,22 +40,22 @@ public class AuthMicrosoftRequest extends AuthDefaultRequest { ...@@ -43,22 +40,22 @@ public class AuthMicrosoftRequest extends AuthDefaultRequest {
Map<String, Object> paramMap = new HashMap<>(6); Map<String, Object> paramMap = new HashMap<>(6);
HttpUtil.decodeParamMap(accessTokenUrl, "UTF-8").forEach(paramMap::put); HttpUtil.decodeParamMap(accessTokenUrl, "UTF-8").forEach(paramMap::put);
HttpResponse response = HttpRequest.post(accessTokenUrl) HttpResponse response = HttpRequest.post(accessTokenUrl)
.header("Host", "https://login.microsoftonline.com") .header("Host", "https://login.microsoftonline.com")
.header("Content-Type", "application/x-www-form-urlencoded") .header("Content-Type", "application/x-www-form-urlencoded")
.form(paramMap) .form(paramMap)
.execute(); .execute();
String accessTokenStr = response.body(); String accessTokenStr = response.body();
JSONObject accessTokenObject = JSONObject.parseObject(accessTokenStr); JSONObject accessTokenObject = JSONObject.parseObject(accessTokenStr);
this.checkResponse(accessTokenObject); this.checkResponse(accessTokenObject);
return AuthToken.builder() return AuthToken.builder()
.accessToken(accessTokenObject.getString("access_token")) .accessToken(accessTokenObject.getString("access_token"))
.expireIn(accessTokenObject.getIntValue("expires_in")) .expireIn(accessTokenObject.getIntValue("expires_in"))
.scope(accessTokenObject.getString("scope")) .scope(accessTokenObject.getString("scope"))
.tokenType(accessTokenObject.getString("token_type")) .tokenType(accessTokenObject.getString("token_type"))
.refreshToken(accessTokenObject.getString("refresh_token")) .refreshToken(accessTokenObject.getString("refresh_token"))
.build(); .build();
} }
private void checkResponse(JSONObject response) { private void checkResponse(JSONObject response) {
...@@ -72,21 +69,19 @@ public class AuthMicrosoftRequest extends AuthDefaultRequest { ...@@ -72,21 +69,19 @@ public class AuthMicrosoftRequest extends AuthDefaultRequest {
String token = authToken.getAccessToken(); String token = authToken.getAccessToken();
String tokenType = authToken.getTokenType(); String tokenType = authToken.getTokenType();
String jwt = tokenType + " " + token; String jwt = tokenType + " " + token;
HttpResponse response = HttpRequest.get(this.urlBuilder.getUserInfoUrl(AuthUserInfoEntity.builder().build())) HttpResponse response = HttpRequest.get(userInfoUrl(authToken)).header("Authorization", jwt).execute();
.header("Authorization", jwt)
.execute();
String userInfo = response.body(); String userInfo = response.body();
JSONObject object = JSONObject.parseObject(userInfo); JSONObject object = JSONObject.parseObject(userInfo);
return AuthUser.builder() return AuthUser.builder()
.uuid(object.getString("id")) .uuid(object.getString("id"))
.username(object.getString("userPrincipalName")) .username(object.getString("userPrincipalName"))
.nickname(object.getString("displayName")) .nickname(object.getString("displayName"))
.location(object.getString("officeLocation")) .location(object.getString("officeLocation"))
.email(object.getString("mail")) .email(object.getString("mail"))
.gender(AuthUserGender.UNKNOWN) .gender(AuthUserGender.UNKNOWN)
.token(authToken) .token(authToken)
.source(AuthSource.MICROSOFT) .source(AuthSource.MICROSOFT)
.build(); .build();
} }
/** /**
...@@ -97,8 +92,73 @@ public class AuthMicrosoftRequest extends AuthDefaultRequest { ...@@ -97,8 +92,73 @@ public class AuthMicrosoftRequest extends AuthDefaultRequest {
*/ */
@Override @Override
public AuthResponse refresh(AuthToken authToken) { public AuthResponse refresh(AuthToken authToken) {
String refreshTokenUrl = this.urlBuilder.getRefreshUrl(authToken.getRefreshToken()); return AuthResponse.builder()
.code(AuthResponseStatus.SUCCESS.getCode())
.data(getToken(refreshTokenUrl(authToken.getRefreshToken())))
.build();
}
/**
* 返回认证url,可自行跳转页面
*
* @return 返回授权地址
*/
@Override
public String authorize() {
return UrlBuilder.fromBaseUrl(source.authorize())
.queryParam("response_type", "code")
.queryParam("client_id", config.getClientId())
.queryParam("redirect_uri", config.getRedirectUri())
.queryParam("response_mode", "query")
.queryParam("scope", "offline_access%20user.read%20mail.read")
.queryParam("state", getRealState(config.getState()))
.build();
}
/**
* 返回获取accessToken的url
*
* @param code
* @return 返回获取accessToken的url
*/
@Override
protected String accessTokenUrl(String code) {
return UrlBuilder.fromBaseUrl(source.accessToken())
.queryParam("code", code)
.queryParam("client_id", config.getClientId())
.queryParam("client_secret", config.getClientSecret())
.queryParam("grant_type", "authorization_code")
.queryParam("scope", "user.read%20mail.read")
.queryParam("redirect_uri", config.getRedirectUri())
.build();
}
/**
* 返回获取userInfo的url
*
* @param authToken
* @return 返回获取userInfo的url
*/
@Override
protected String userInfoUrl(AuthToken authToken) {
return UrlBuilder.fromBaseUrl(source.userInfo()).build();
}
return AuthResponse.builder().code(AuthResponseStatus.SUCCESS.getCode()).data(getToken(refreshTokenUrl)).build(); /**
* 返回获取accessToken的url
*
* @param refreshToken
* @return 返回获取accessToken的url
*/
@Override
protected String refreshTokenUrl(String refreshToken) {
return UrlBuilder.fromBaseUrl(source.refresh())
.queryParam("client_id", config.getClientId())
.queryParam("client_secret", config.getClientSecret())
.queryParam("refresh_token", refreshToken)
.queryParam("grant_type", "refresh_token")
.queryParam("scope", "user.read%20mail.read")
.queryParam("redirect_uri", config.getRedirectUri())
.build();
} }
} }
package me.zhyd.oauth.request; package me.zhyd.oauth.request;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse; import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import me.zhyd.oauth.config.AuthConfig; import me.zhyd.oauth.config.AuthConfig;
...@@ -10,8 +9,7 @@ import me.zhyd.oauth.model.AuthCallback; ...@@ -10,8 +9,7 @@ import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthToken; import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser; import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.model.AuthUserGender; import me.zhyd.oauth.model.AuthUserGender;
import me.zhyd.oauth.url.AuthOschinaUrlBuilder; import me.zhyd.oauth.utils.UrlBuilder;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
/** /**
* oschina登录 * oschina登录
...@@ -23,46 +21,74 @@ import me.zhyd.oauth.url.entity.AuthUserInfoEntity; ...@@ -23,46 +21,74 @@ import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
public class AuthOschinaRequest extends AuthDefaultRequest { public class AuthOschinaRequest extends AuthDefaultRequest {
public AuthOschinaRequest(AuthConfig config) { public AuthOschinaRequest(AuthConfig config) {
super(config, AuthSource.OSCHINA, new AuthOschinaUrlBuilder()); super(config, AuthSource.OSCHINA);
} }
@Override @Override
protected AuthToken getAccessToken(AuthCallback authCallback) { protected AuthToken getAccessToken(AuthCallback authCallback) {
String accessTokenUrl = this.urlBuilder.getAccessTokenUrl(authCallback.getCode()); HttpResponse response = doPostAuthorizationCode(authCallback.getCode());
HttpResponse response = HttpRequest.post(accessTokenUrl).execute();
JSONObject accessTokenObject = JSONObject.parseObject(response.body()); JSONObject accessTokenObject = JSONObject.parseObject(response.body());
if (accessTokenObject.containsKey("error")) { if (accessTokenObject.containsKey("error")) {
throw new AuthException("Unable to get token from oschina using code [" + authCallback.getCode() + "]: " + accessTokenObject); throw new AuthException("Unable to get token from oschina using code [" + authCallback.getCode() + "]: " + accessTokenObject);
} }
return AuthToken.builder() return AuthToken.builder()
.accessToken(accessTokenObject.getString("access_token")) .accessToken(accessTokenObject.getString("access_token"))
.refreshToken(accessTokenObject.getString("refresh_token")) .refreshToken(accessTokenObject.getString("refresh_token"))
.uid(accessTokenObject.getString("uid")) .uid(accessTokenObject.getString("uid"))
.expireIn(accessTokenObject.getIntValue("expires_in")) .expireIn(accessTokenObject.getIntValue("expires_in"))
.build(); .build();
} }
@Override @Override
protected AuthUser getUserInfo(AuthToken authToken) { protected AuthUser getUserInfo(AuthToken authToken) {
String accessToken = authToken.getAccessToken(); HttpResponse response = doGetUserInfo(authToken);
HttpResponse response = HttpRequest.get(this.urlBuilder.getUserInfoUrl(AuthUserInfoEntity.builder()
.accessToken(accessToken)
.build())).execute();
JSONObject object = JSONObject.parseObject(response.body()); JSONObject object = JSONObject.parseObject(response.body());
if (object.containsKey("error")) { if (object.containsKey("error")) {
throw new AuthException(object.getString("error_description")); throw new AuthException(object.getString("error_description"));
} }
return AuthUser.builder() return AuthUser.builder()
.uuid(object.getString("id")) .uuid(object.getString("id"))
.username(object.getString("name")) .username(object.getString("name"))
.nickname(object.getString("name")) .nickname(object.getString("name"))
.avatar(object.getString("avatar")) .avatar(object.getString("avatar"))
.blog(object.getString("url")) .blog(object.getString("url"))
.location(object.getString("location")) .location(object.getString("location"))
.gender(AuthUserGender.getRealGender(object.getString("gender"))) .gender(AuthUserGender.getRealGender(object.getString("gender")))
.email(object.getString("email")) .email(object.getString("email"))
.token(authToken) .token(authToken)
.source(AuthSource.OSCHINA) .source(AuthSource.OSCHINA)
.build(); .build();
}
/**
* 返回获取accessToken的url
*
* @param code
* @return 返回获取accessToken的url
*/
@Override
protected String accessTokenUrl(String code) {
return UrlBuilder.fromBaseUrl(source.accessToken())
.queryParam("code", code)
.queryParam("client_id", config.getClientId())
.queryParam("client_secret", config.getClientSecret())
.queryParam("grant_type", "authorization_code")
.queryParam("redirect_uri", config.getRedirectUri())
.queryParam("dataType", "json")
.build();
}
/**
* 返回获取userInfo的url
*
* @param authToken
* @return 返回获取userInfo的url
*/
@Override
protected String userInfoUrl(AuthToken authToken) {
return UrlBuilder.fromBaseUrl(source.userInfo())
.queryParam("access_token", authToken.getAccessToken())
.queryParam("dataType", "json")
.build();
} }
} }
...@@ -11,10 +11,9 @@ import me.zhyd.oauth.model.AuthCallback; ...@@ -11,10 +11,9 @@ import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthToken; import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser; import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.model.AuthUserGender; import me.zhyd.oauth.model.AuthUserGender;
import me.zhyd.oauth.url.AuthQqUrlBuilder;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
import me.zhyd.oauth.utils.GlobalAuthUtil; import me.zhyd.oauth.utils.GlobalAuthUtil;
import me.zhyd.oauth.utils.StringUtils; import me.zhyd.oauth.utils.StringUtils;
import me.zhyd.oauth.utils.UrlBuilder;
import java.util.Map; import java.util.Map;
...@@ -28,34 +27,27 @@ import java.util.Map; ...@@ -28,34 +27,27 @@ import java.util.Map;
*/ */
public class AuthQqRequest extends AuthDefaultRequest { public class AuthQqRequest extends AuthDefaultRequest {
public AuthQqRequest(AuthConfig config) { public AuthQqRequest(AuthConfig config) {
super(config, AuthSource.QQ, new AuthQqUrlBuilder()); super(config, AuthSource.QQ);
} }
@Override @Override
protected AuthToken getAccessToken(AuthCallback authCallback) { protected AuthToken getAccessToken(AuthCallback authCallback) {
String accessTokenUrl = this.urlBuilder.getAccessTokenUrl(authCallback.getCode()); HttpResponse response = doGetAuthorizationCode(authCallback.getCode());
HttpResponse response = HttpRequest.get(accessTokenUrl).execute();
Map<String, String> accessTokenObject = GlobalAuthUtil.parseStringToMap(response.body()); Map<String, String> accessTokenObject = GlobalAuthUtil.parseStringToMap(response.body());
if (!accessTokenObject.containsKey("access_token")) { if (!accessTokenObject.containsKey("access_token")) {
throw new AuthException("Unable to get token from qq using code [" + authCallback.getCode() + "]: " + accessTokenObject); throw new AuthException("Unable to get token from qq using code [" + authCallback.getCode() + "]: " + accessTokenObject);
} }
return AuthToken.builder() return AuthToken.builder()
.accessToken(accessTokenObject.get("access_token")) .accessToken(accessTokenObject.get("access_token"))
.expireIn(Integer.valueOf(accessTokenObject.get("expires_in"))) .expireIn(Integer.valueOf(accessTokenObject.get("expires_in")))
.refreshToken(accessTokenObject.get("refresh_token")) .refreshToken(accessTokenObject.get("refresh_token"))
.build(); .build();
} }
@Override @Override
protected AuthUser getUserInfo(AuthToken authToken) { protected AuthUser getUserInfo(AuthToken authToken) {
String accessToken = authToken.getAccessToken();
String openId = this.getOpenId(authToken); String openId = this.getOpenId(authToken);
HttpResponse response = HttpRequest.get(this.urlBuilder.getUserInfoUrl(AuthUserInfoEntity.builder() HttpResponse response = doGetUserInfo(authToken);
.clientId(config.getClientId())
.accessToken(accessToken)
.openId(openId)
.build()))
.execute();
JSONObject object = JSONObject.parseObject(response.body()); JSONObject object = JSONObject.parseObject(response.body());
if (object.getIntValue("ret") != 0) { if (object.getIntValue("ret") != 0) {
throw new AuthException(object.getString("msg")); throw new AuthException(object.getString("msg"));
...@@ -67,20 +59,22 @@ public class AuthQqRequest extends AuthDefaultRequest { ...@@ -67,20 +59,22 @@ public class AuthQqRequest extends AuthDefaultRequest {
String location = String.format("%s-%s", object.getString("province"), object.getString("city")); String location = String.format("%s-%s", object.getString("province"), object.getString("city"));
return AuthUser.builder() return AuthUser.builder()
.username(object.getString("nickname")) .username(object.getString("nickname"))
.nickname(object.getString("nickname")) .nickname(object.getString("nickname"))
.avatar(avatar) .avatar(avatar)
.location(location) .location(location)
.uuid(openId) .uuid(openId)
.gender(AuthUserGender.getRealGender(object.getString("gender"))) .gender(AuthUserGender.getRealGender(object.getString("gender")))
.token(authToken) .token(authToken)
.source(AuthSource.QQ) .source(AuthSource.QQ)
.build(); .build();
} }
private String getOpenId(AuthToken authToken) { private String getOpenId(AuthToken authToken) {
String accessToken = authToken.getAccessToken(); HttpResponse response = HttpRequest.get(UrlBuilder.fromBaseUrl("https://graph.qq.com/oauth2.0/me")
HttpResponse response = HttpRequest.get(this.urlBuilder.getOpenIdUrl(accessToken, config.isUnionId())).execute(); .queryParam("access_token", authToken.getAccessToken())
.queryParam("unionid", config.isUnionId() ? 1 : 0)
.build()).execute();
if (response.isOk()) { if (response.isOk()) {
String body = response.body(); String body = response.body();
String removePrefix = StrUtil.replace(body, "callback(", ""); String removePrefix = StrUtil.replace(body, "callback(", "");
...@@ -99,4 +93,19 @@ public class AuthQqRequest extends AuthDefaultRequest { ...@@ -99,4 +93,19 @@ public class AuthQqRequest extends AuthDefaultRequest {
throw new AuthException("request error"); throw new AuthException("request error");
} }
/**
* 返回获取userInfo的url
*
* @param authToken
* @return 返回获取userInfo的url
*/
@Override
protected String userInfoUrl(AuthToken authToken) {
return UrlBuilder.fromBaseUrl(source.userInfo())
.queryParam("access_token", authToken.getAccessToken())
.queryParam("oauth_consumer_key", config.getClientId())
.queryParam("openid", authToken.getOpenId())
.build();
}
} }
package me.zhyd.oauth.request; package me.zhyd.oauth.request;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse; import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
...@@ -10,8 +9,7 @@ import me.zhyd.oauth.model.AuthCallback; ...@@ -10,8 +9,7 @@ import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthToken; import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser; import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.model.AuthUserGender; import me.zhyd.oauth.model.AuthUserGender;
import me.zhyd.oauth.url.AuthRenrenUrlBuilder; import me.zhyd.oauth.utils.UrlBuilder;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
import java.util.Objects; import java.util.Objects;
...@@ -27,13 +25,12 @@ import static me.zhyd.oauth.config.AuthSource.RENREN; ...@@ -27,13 +25,12 @@ import static me.zhyd.oauth.config.AuthSource.RENREN;
public class AuthRenrenRequest extends AuthDefaultRequest { public class AuthRenrenRequest extends AuthDefaultRequest {
public AuthRenrenRequest(AuthConfig config) { public AuthRenrenRequest(AuthConfig config) {
super(config, RENREN, new AuthRenrenUrlBuilder()); super(config, RENREN);
} }
@Override @Override
protected AuthToken getAccessToken(AuthCallback authCallback) { protected AuthToken getAccessToken(AuthCallback authCallback) {
String accessTokenUrl = this.urlBuilder.getAccessTokenUrl(authCallback.getCode()); HttpResponse response = doPostAuthorizationCode(authCallback.getCode());
HttpResponse response = HttpRequest.post(accessTokenUrl).execute();
JSONObject accessTokenObject = JSONObject.parseObject(response.body()); JSONObject accessTokenObject = JSONObject.parseObject(response.body());
if (!response.isOk()) { if (!response.isOk()) {
throw new AuthException("Unable to get token from renren using code [" + authCallback.getCode() + "]: " + accessTokenObject); throw new AuthException("Unable to get token from renren using code [" + authCallback.getCode() + "]: " + accessTokenObject);
...@@ -48,11 +45,7 @@ public class AuthRenrenRequest extends AuthDefaultRequest { ...@@ -48,11 +45,7 @@ public class AuthRenrenRequest extends AuthDefaultRequest {
@Override @Override
protected AuthUser getUserInfo(AuthToken authToken) { protected AuthUser getUserInfo(AuthToken authToken) {
String accessToken = authToken.getAccessToken(); HttpResponse response = doGetUserInfo(authToken);
HttpResponse response = HttpRequest.get(this.urlBuilder.getUserInfoUrl(AuthUserInfoEntity.builder()
.openId(authToken.getOpenId())
.accessToken(accessToken)
.build())).execute();
JSONObject userObj = JSONObject.parseObject(response.body()).getJSONObject("response"); JSONObject userObj = JSONObject.parseObject(response.body()).getJSONObject("response");
return AuthUser.builder() return AuthUser.builder()
...@@ -89,4 +82,18 @@ public class AuthRenrenRequest extends AuthDefaultRequest { ...@@ -89,4 +82,18 @@ public class AuthRenrenRequest extends AuthDefaultRequest {
} }
return jsonArray.getJSONObject(0).getString("name"); return jsonArray.getJSONObject(0).getString("name");
} }
/**
* 返回获取userInfo的url
*
* @param authToken
* @return 返回获取userInfo的url
*/
@Override
protected String userInfoUrl(AuthToken authToken) {
return UrlBuilder.fromBaseUrl(source.userInfo())
.queryParam("access_token", authToken.getAccessToken())
.queryParam("userId", authToken.getOpenId())
.build();
}
} }
package me.zhyd.oauth.request; package me.zhyd.oauth.request;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse; import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import me.zhyd.oauth.config.AuthConfig; import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthSource; import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException; import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.*; import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.url.AuthTaobaoUrlBuilder; import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.model.AuthUserGender;
import me.zhyd.oauth.utils.GlobalAuthUtil; import me.zhyd.oauth.utils.GlobalAuthUtil;
import me.zhyd.oauth.utils.UrlBuilder;
/** /**
* 淘宝登录 * 淘宝登录
...@@ -20,7 +22,7 @@ import me.zhyd.oauth.utils.GlobalAuthUtil; ...@@ -20,7 +22,7 @@ import me.zhyd.oauth.utils.GlobalAuthUtil;
public class AuthTaobaoRequest extends AuthDefaultRequest { public class AuthTaobaoRequest extends AuthDefaultRequest {
public AuthTaobaoRequest(AuthConfig config) { public AuthTaobaoRequest(AuthConfig config) {
super(config, AuthSource.TAOBAO, new AuthTaobaoUrlBuilder()); super(config, AuthSource.TAOBAO);
} }
@Override @Override
...@@ -30,8 +32,7 @@ public class AuthTaobaoRequest extends AuthDefaultRequest { ...@@ -30,8 +32,7 @@ public class AuthTaobaoRequest extends AuthDefaultRequest {
@Override @Override
protected AuthUser getUserInfo(AuthToken authToken) { protected AuthUser getUserInfo(AuthToken authToken) {
String accessCode = authToken.getAccessCode(); HttpResponse response = doPostAuthorizationCode(authToken.getAccessCode());
HttpResponse response = HttpRequest.post(this.urlBuilder.getAccessTokenUrl(accessCode)).execute();
JSONObject accessTokenObject = JSONObject.parseObject(response.body()); JSONObject accessTokenObject = JSONObject.parseObject(response.body());
if (accessTokenObject.containsKey("error")) { if (accessTokenObject.containsKey("error")) {
throw new AuthException(accessTokenObject.getString("error_description")); throw new AuthException(accessTokenObject.getString("error_description"));
...@@ -44,12 +45,28 @@ public class AuthTaobaoRequest extends AuthDefaultRequest { ...@@ -44,12 +45,28 @@ public class AuthTaobaoRequest extends AuthDefaultRequest {
String nick = GlobalAuthUtil.urlDecode(accessTokenObject.getString("taobao_user_nick")); String nick = GlobalAuthUtil.urlDecode(accessTokenObject.getString("taobao_user_nick"));
return AuthUser.builder() return AuthUser.builder()
.uuid(accessTokenObject.getString("taobao_user_id")) .uuid(accessTokenObject.getString("taobao_user_id"))
.username(nick) .username(nick)
.nickname(nick) .nickname(nick)
.gender(AuthUserGender.UNKNOWN) .gender(AuthUserGender.UNKNOWN)
.token(authToken) .token(authToken)
.source(AuthSource.TAOBAO) .source(AuthSource.TAOBAO)
.build(); .build();
}
/**
* 返回认证url,可自行跳转页面
*
* @return 返回授权地址
*/
@Override
public String authorize() {
return UrlBuilder.fromBaseUrl(source.authorize())
.queryParam("response_type", "code")
.queryParam("client_id", config.getClientId())
.queryParam("redirect_uri", config.getRedirectUri())
.queryParam("state", getRealState(config.getState()))
.queryParam("view", "web")
.build();
} }
} }
...@@ -7,7 +7,6 @@ import me.zhyd.oauth.config.AuthConfig; ...@@ -7,7 +7,6 @@ import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthSource; import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException; import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.*; import me.zhyd.oauth.model.*;
import me.zhyd.oauth.url.AuthTeambitionUrlBuilder;
/** /**
* Teambition授权登录 * Teambition授权登录
...@@ -19,7 +18,7 @@ import me.zhyd.oauth.url.AuthTeambitionUrlBuilder; ...@@ -19,7 +18,7 @@ import me.zhyd.oauth.url.AuthTeambitionUrlBuilder;
public class AuthTeambitionRequest extends AuthDefaultRequest { public class AuthTeambitionRequest extends AuthDefaultRequest {
public AuthTeambitionRequest(AuthConfig config) { public AuthTeambitionRequest(AuthConfig config) {
super(config, AuthSource.TEAMBITION, new AuthTeambitionUrlBuilder()); super(config, AuthSource.TEAMBITION);
} }
/** /**
...@@ -28,30 +27,29 @@ public class AuthTeambitionRequest extends AuthDefaultRequest { ...@@ -28,30 +27,29 @@ public class AuthTeambitionRequest extends AuthDefaultRequest {
*/ */
@Override @Override
protected AuthToken getAccessToken(AuthCallback authCallback) { protected AuthToken getAccessToken(AuthCallback authCallback) {
String accessTokenUrl = this.urlBuilder.getAccessTokenUrl(authCallback.getCode()); HttpResponse response = HttpRequest.post(source.accessToken())
HttpResponse response = HttpRequest.post(accessTokenUrl) .form("client_id", config.getClientId())
.form("client_id", config.getClientId()) .form("client_secret", config.getClientSecret())
.form("client_secret", config.getClientSecret()) .form("code", authCallback.getCode())
.form("code", authCallback.getCode()) .form("grant_type", "code")
.form("grant_type", "code") .execute();
.execute();
JSONObject accessTokenObject = JSONObject.parseObject(response.body()); JSONObject accessTokenObject = JSONObject.parseObject(response.body());
this.checkResponse(accessTokenObject); this.checkResponse(accessTokenObject);
return AuthToken.builder() return AuthToken.builder()
.accessToken(accessTokenObject.getString("access_token")) .accessToken(accessTokenObject.getString("access_token"))
.refreshToken(accessTokenObject.getString("refresh_token")) .refreshToken(accessTokenObject.getString("refresh_token"))
.build(); .build();
} }
@Override @Override
protected AuthUser getUserInfo(AuthToken authToken) { protected AuthUser getUserInfo(AuthToken authToken) {
String accessToken = authToken.getAccessToken(); String accessToken = authToken.getAccessToken();
HttpResponse response = HttpRequest.get(this.urlBuilder.getUserInfoUrl(null)) HttpResponse response = HttpRequest.get(source.userInfo())
.header("Authorization", "OAuth2 " + accessToken) .header("Authorization", "OAuth2 " + accessToken)
.execute(); .execute();
JSONObject object = JSONObject.parseObject(response.body()); JSONObject object = JSONObject.parseObject(response.body());
this.checkResponse(object); this.checkResponse(object);
...@@ -59,39 +57,38 @@ public class AuthTeambitionRequest extends AuthDefaultRequest { ...@@ -59,39 +57,38 @@ public class AuthTeambitionRequest extends AuthDefaultRequest {
authToken.setUid(object.getString("_id")); authToken.setUid(object.getString("_id"));
return AuthUser.builder() return AuthUser.builder()
.uuid(object.getString("_id")) .uuid(object.getString("_id"))
.username(object.getString("name")) .username(object.getString("name"))
.nickname(object.getString("name")) .nickname(object.getString("name"))
.avatar(object.getString("avatarUrl")) .avatar(object.getString("avatarUrl"))
.blog(object.getString("website")) .blog(object.getString("website"))
.location(object.getString("location")) .location(object.getString("location"))
.email(object.getString("email")) .email(object.getString("email"))
.gender(AuthUserGender.UNKNOWN) .gender(AuthUserGender.UNKNOWN)
.token(authToken) .token(authToken)
.source(AuthSource.TEAMBITION) .source(AuthSource.TEAMBITION)
.build(); .build();
} }
@Override @Override
public AuthResponse refresh(AuthToken oldToken) { public AuthResponse refresh(AuthToken oldToken) {
String uid = oldToken.getUid(); String uid = oldToken.getUid();
String refreshToken = oldToken.getRefreshToken(); String refreshToken = oldToken.getRefreshToken();
String refreshTokenUrl = this.urlBuilder.getRefreshUrl(refreshToken); HttpResponse response = HttpRequest.post(source.refresh())
HttpResponse response = HttpRequest.post(refreshTokenUrl) .form("_userId", uid)
.form("_userId", uid) .form("refresh_token", refreshToken)
.form("refresh_token", refreshToken) .execute();
.execute();
JSONObject refreshTokenObject = JSONObject.parseObject(response.body()); JSONObject refreshTokenObject = JSONObject.parseObject(response.body());
this.checkResponse(refreshTokenObject); this.checkResponse(refreshTokenObject);
return AuthResponse.builder() return AuthResponse.builder()
.code(AuthResponseStatus.SUCCESS.getCode()) .code(AuthResponseStatus.SUCCESS.getCode())
.data(AuthToken.builder() .data(AuthToken.builder()
.accessToken(refreshTokenObject.getString("access_token")) .accessToken(refreshTokenObject.getString("access_token"))
.refreshToken(refreshTokenObject.getString("refresh_token")) .refreshToken(refreshTokenObject.getString("refresh_token"))
.build()) .build())
.build(); .build();
} }
/** /**
......
package me.zhyd.oauth.request; package me.zhyd.oauth.request;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse; import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import me.zhyd.oauth.config.AuthConfig; import me.zhyd.oauth.config.AuthConfig;
...@@ -10,8 +9,7 @@ import me.zhyd.oauth.model.AuthCallback; ...@@ -10,8 +9,7 @@ import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthToken; import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser; import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.model.AuthUserGender; import me.zhyd.oauth.model.AuthUserGender;
import me.zhyd.oauth.url.AuthTencentCloudUrlBuilder; import me.zhyd.oauth.utils.UrlBuilder;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
/** /**
* 腾讯云登录 * 腾讯云登录
...@@ -23,48 +21,61 @@ import me.zhyd.oauth.url.entity.AuthUserInfoEntity; ...@@ -23,48 +21,61 @@ import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
public class AuthTencentCloudRequest extends AuthDefaultRequest { public class AuthTencentCloudRequest extends AuthDefaultRequest {
public AuthTencentCloudRequest(AuthConfig config) { public AuthTencentCloudRequest(AuthConfig config) {
super(config, AuthSource.TENCENT_CLOUD, new AuthTencentCloudUrlBuilder()); super(config, AuthSource.TENCENT_CLOUD);
} }
@Override @Override
protected AuthToken getAccessToken(AuthCallback authCallback) { protected AuthToken getAccessToken(AuthCallback authCallback) {
String accessTokenUrl = this.urlBuilder.getAccessTokenUrl(authCallback.getCode()); HttpResponse response = doGetAuthorizationCode(authCallback.getCode());
HttpResponse response = HttpRequest.get(accessTokenUrl).execute();
JSONObject accessTokenObject = JSONObject.parseObject(response.body()); JSONObject accessTokenObject = JSONObject.parseObject(response.body());
if (accessTokenObject.getIntValue("code") != 0) { if (accessTokenObject.getIntValue("code") != 0) {
throw new AuthException("Unable to get token from tencent cloud using code [" + authCallback.getCode() + "]: " + accessTokenObject.get("msg")); throw new AuthException("Unable to get token from tencent cloud using code [" + authCallback.getCode() + "]: " + accessTokenObject
.get("msg"));
} }
return AuthToken.builder() return AuthToken.builder()
.accessToken(accessTokenObject.getString("access_token")) .accessToken(accessTokenObject.getString("access_token"))
.expireIn(accessTokenObject.getIntValue("expires_in")) .expireIn(accessTokenObject.getIntValue("expires_in"))
.refreshToken(accessTokenObject.getString("refresh_token")) .refreshToken(accessTokenObject.getString("refresh_token"))
.build(); .build();
} }
@Override @Override
protected AuthUser getUserInfo(AuthToken authToken) { protected AuthUser getUserInfo(AuthToken authToken) {
String accessToken = authToken.getAccessToken(); HttpResponse response = doGetUserInfo(authToken);
HttpResponse response = HttpRequest.get(this.urlBuilder.getUserInfoUrl(AuthUserInfoEntity.builder()
.accessToken(accessToken)
.build())).execute();
JSONObject object = JSONObject.parseObject(response.body()); JSONObject object = JSONObject.parseObject(response.body());
if (object.getIntValue("code") != 0) { if (object.getIntValue("code") != 0) {
throw new AuthException(object.getString("msg")); throw new AuthException(object.getString("msg"));
} }
object = object.getJSONObject("data"); object = object.getJSONObject("data");
return AuthUser.builder() return AuthUser.builder()
.uuid(object.getString("id")) .uuid(object.getString("id"))
.username(object.getString("name")) .username(object.getString("name"))
.avatar("https://dev.tencent.com/" + object.getString("avatar")) .avatar("https://dev.tencent.com/" + object.getString("avatar"))
.blog("https://dev.tencent.com/" + object.getString("path")) .blog("https://dev.tencent.com/" + object.getString("path"))
.nickname(object.getString("name")) .nickname(object.getString("name"))
.company(object.getString("company")) .company(object.getString("company"))
.location(object.getString("location")) .location(object.getString("location"))
.gender(AuthUserGender.getRealGender(object.getString("sex"))) .gender(AuthUserGender.getRealGender(object.getString("sex")))
.email(object.getString("email")) .email(object.getString("email"))
.remark(object.getString("slogan")) .remark(object.getString("slogan"))
.token(authToken) .token(authToken)
.source(AuthSource.TENCENT_CLOUD) .source(AuthSource.TENCENT_CLOUD)
.build(); .build();
}
/**
* 返回认证url,可自行跳转页面
*
* @return 返回授权地址
*/
@Override
public String authorize() {
return UrlBuilder.fromBaseUrl(source.authorize())
.queryParam("response_type", "code")
.queryParam("client_id", config.getClientId())
.queryParam("redirect_uri", config.getRedirectUri())
.queryParam("scope", "user")
.queryParam("state", getRealState(config.getState()))
.build();
} }
} }
package me.zhyd.oauth.request; package me.zhyd.oauth.request;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse; import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import me.zhyd.oauth.config.AuthConfig; import me.zhyd.oauth.config.AuthConfig;
...@@ -11,8 +10,7 @@ import me.zhyd.oauth.model.AuthCallback; ...@@ -11,8 +10,7 @@ import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthToken; import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser; import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.model.AuthUserGender; import me.zhyd.oauth.model.AuthUserGender;
import me.zhyd.oauth.url.AuthToutiaoUrlBuilder; import me.zhyd.oauth.utils.UrlBuilder;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
/** /**
* 今日头条登录 * 今日头条登录
...@@ -24,32 +22,29 @@ import me.zhyd.oauth.url.entity.AuthUserInfoEntity; ...@@ -24,32 +22,29 @@ import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
public class AuthToutiaoRequest extends AuthDefaultRequest { public class AuthToutiaoRequest extends AuthDefaultRequest {
public AuthToutiaoRequest(AuthConfig config) { public AuthToutiaoRequest(AuthConfig config) {
super(config, AuthSource.TOUTIAO, new AuthToutiaoUrlBuilder()); super(config, AuthSource.TOUTIAO);
} }
@Override @Override
protected AuthToken getAccessToken(AuthCallback authCallback) { protected AuthToken getAccessToken(AuthCallback authCallback) {
String accessTokenUrl = this.urlBuilder.getAccessTokenUrl(authCallback.getCode()); HttpResponse response = doGetAuthorizationCode(authCallback.getCode());
HttpResponse response = HttpRequest.get(accessTokenUrl).execute();
JSONObject accessTokenObject = JSONObject.parseObject(response.body()); JSONObject accessTokenObject = JSONObject.parseObject(response.body());
if (accessTokenObject.containsKey("error_code")) { if (accessTokenObject.containsKey("error_code")) {
throw new AuthException(AuthToutiaoErrorCode.getErrorCode(accessTokenObject.getIntValue("error_code")).getDesc()); throw new AuthException(AuthToutiaoErrorCode.getErrorCode(accessTokenObject.getIntValue("error_code"))
.getDesc());
} }
return AuthToken.builder() return AuthToken.builder()
.accessToken(accessTokenObject.getString("access_token")) .accessToken(accessTokenObject.getString("access_token"))
.expireIn(accessTokenObject.getIntValue("expires_in")) .expireIn(accessTokenObject.getIntValue("expires_in"))
.openId(accessTokenObject.getString("open_id")) .openId(accessTokenObject.getString("open_id"))
.build(); .build();
} }
@Override @Override
protected AuthUser getUserInfo(AuthToken authToken) { protected AuthUser getUserInfo(AuthToken authToken) {
HttpResponse userResponse = HttpRequest.get(this.urlBuilder.getUserInfoUrl(AuthUserInfoEntity.builder() HttpResponse userResponse = doGetUserInfo(authToken);
.clientId(config.getClientId())
.accessToken(authToken.getAccessToken())
.build())).execute();
JSONObject userProfile = JSONObject.parseObject(userResponse.body()); JSONObject userProfile = JSONObject.parseObject(userResponse.body());
...@@ -63,14 +58,61 @@ public class AuthToutiaoRequest extends AuthDefaultRequest { ...@@ -63,14 +58,61 @@ public class AuthToutiaoRequest extends AuthDefaultRequest {
String anonymousUserName = "匿名用户"; String anonymousUserName = "匿名用户";
return AuthUser.builder() return AuthUser.builder()
.uuid(user.getString("uid")) .uuid(user.getString("uid"))
.username(isAnonymousUser ? anonymousUserName : user.getString("screen_name")) .username(isAnonymousUser ? anonymousUserName : user.getString("screen_name"))
.nickname(isAnonymousUser ? anonymousUserName : user.getString("screen_name")) .nickname(isAnonymousUser ? anonymousUserName : user.getString("screen_name"))
.avatar(user.getString("avatar_url")) .avatar(user.getString("avatar_url"))
.remark(user.getString("description")) .remark(user.getString("description"))
.gender(AuthUserGender.getRealGender(user.getString("gender"))) .gender(AuthUserGender.getRealGender(user.getString("gender")))
.token(authToken) .token(authToken)
.source(AuthSource.TOUTIAO) .source(AuthSource.TOUTIAO)
.build(); .build();
}
/**
* 返回认证url,可自行跳转页面
*
* @return 返回授权地址
*/
@Override
public String authorize() {
return UrlBuilder.fromBaseUrl(source.authorize())
.queryParam("response_type", "code")
.queryParam("client_key", config.getClientId())
.queryParam("redirect_uri", config.getRedirectUri())
.queryParam("state", getRealState(config.getState()))
.queryParam("auth_only", 1)
.queryParam("display", 0)
.build();
}
/**
* 返回获取accessToken的url
*
* @param code
* @return 返回获取accessToken的url
*/
@Override
protected String accessTokenUrl(String code) {
return UrlBuilder.fromBaseUrl(source.accessToken())
.queryParam("code", code)
.queryParam("client_key", config.getClientId())
.queryParam("client_secret", config.getClientSecret())
.queryParam("grant_type", "authorization_code")
.build();
}
/**
* 返回获取userInfo的url
*
* @param authToken
* @return 返回获取userInfo的url
*/
@Override
protected String userInfoUrl(AuthToken authToken) {
return UrlBuilder.fromBaseUrl(source.userInfo())
.queryParam("client_key", config.getClientId())
.queryParam("access_token", authToken.getAccessToken())
.build();
} }
} }
...@@ -7,8 +7,7 @@ import me.zhyd.oauth.config.AuthConfig; ...@@ -7,8 +7,7 @@ import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthSource; import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException; import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.*; import me.zhyd.oauth.model.*;
import me.zhyd.oauth.url.AuthWechatUrlBuilder; import me.zhyd.oauth.utils.UrlBuilder;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
/** /**
* 微信登录 * 微信登录
...@@ -19,7 +18,7 @@ import me.zhyd.oauth.url.entity.AuthUserInfoEntity; ...@@ -19,7 +18,7 @@ import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
*/ */
public class AuthWeChatRequest extends AuthDefaultRequest { public class AuthWeChatRequest extends AuthDefaultRequest {
public AuthWeChatRequest(AuthConfig config) { public AuthWeChatRequest(AuthConfig config) {
super(config, AuthSource.WECHAT, new AuthWechatUrlBuilder()); super(config, AuthSource.WECHAT);
} }
/** /**
...@@ -30,48 +29,42 @@ public class AuthWeChatRequest extends AuthDefaultRequest { ...@@ -30,48 +29,42 @@ public class AuthWeChatRequest extends AuthDefaultRequest {
*/ */
@Override @Override
protected AuthToken getAccessToken(AuthCallback authCallback) { protected AuthToken getAccessToken(AuthCallback authCallback) {
String accessTokenUrl = this.urlBuilder.getAccessTokenUrl(authCallback.getCode()); return this.getToken(accessTokenUrl(authCallback.getCode()));
return this.getToken(accessTokenUrl);
} }
@Override @Override
protected AuthUser getUserInfo(AuthToken authToken) { protected AuthUser getUserInfo(AuthToken authToken) {
String accessToken = authToken.getAccessToken();
String openId = authToken.getOpenId(); String openId = authToken.getOpenId();
HttpResponse response = HttpRequest.get(this.urlBuilder.getUserInfoUrl(AuthUserInfoEntity.builder() HttpResponse response = doGetUserInfo(authToken);
.accessToken(accessToken)
.openId(openId)
.build())).execute();
JSONObject object = JSONObject.parseObject(response.body()); JSONObject object = JSONObject.parseObject(response.body());
this.checkResponse(object); this.checkResponse(object);
String location = String.format("%s-%s-%s", object.getString("country"), object.getString("province"), object.getString("city")); String location = String.format("%s-%s-%s", object.getString("country"), object.getString("province"), object.getString("city"));
if (object.containsKey("unionid")){ if (object.containsKey("unionid")) {
authToken.setUnionId(object.getString("unionid")); authToken.setUnionId(object.getString("unionid"));
} }
return AuthUser.builder() return AuthUser.builder()
.username(object.getString("nickname")) .username(object.getString("nickname"))
.nickname(object.getString("nickname")) .nickname(object.getString("nickname"))
.avatar(object.getString("headimgurl")) .avatar(object.getString("headimgurl"))
.location(location) .location(location)
.uuid(openId) .uuid(openId)
.gender(AuthUserGender.getRealGender(object.getString("sex"))) .gender(AuthUserGender.getRealGender(object.getString("sex")))
.token(authToken) .token(authToken)
.source(AuthSource.WECHAT) .source(AuthSource.WECHAT)
.build(); .build();
} }
@Override @Override
public AuthResponse refresh(AuthToken oldToken) { public AuthResponse refresh(AuthToken oldToken) {
String refreshTokenUrl = this.urlBuilder.getRefreshUrl(oldToken.getRefreshToken());
return AuthResponse.builder() return AuthResponse.builder()
.code(AuthResponseStatus.SUCCESS.getCode()) .code(AuthResponseStatus.SUCCESS.getCode())
.data(this.getToken(refreshTokenUrl)) .data(this.getToken(refreshTokenUrl(oldToken.getRefreshToken())))
.build(); .build();
} }
/** /**
...@@ -98,10 +91,72 @@ public class AuthWeChatRequest extends AuthDefaultRequest { ...@@ -98,10 +91,72 @@ public class AuthWeChatRequest extends AuthDefaultRequest {
this.checkResponse(accessTokenObject); this.checkResponse(accessTokenObject);
return AuthToken.builder() return AuthToken.builder()
.accessToken(accessTokenObject.getString("access_token")) .accessToken(accessTokenObject.getString("access_token"))
.refreshToken(accessTokenObject.getString("refresh_token")) .refreshToken(accessTokenObject.getString("refresh_token"))
.expireIn(accessTokenObject.getIntValue("expires_in")) .expireIn(accessTokenObject.getIntValue("expires_in"))
.openId(accessTokenObject.getString("openid")) .openId(accessTokenObject.getString("openid"))
.build(); .build();
}
/**
* 返回认证url,可自行跳转页面
*
* @return 返回授权地址
*/
@Override
public String authorize() {
return UrlBuilder.fromBaseUrl(source.authorize())
.queryParam("response_type", "code")
.queryParam("appid", config.getClientId())
.queryParam("redirect_uri", config.getRedirectUri())
.queryParam("scope", "snsapi_login")
.queryParam("state", getRealState(config.getState()).concat("#wechat_redirect"))
.build();
}
/**
* 返回获取accessToken的url
*
* @param code
* @return 返回获取accessToken的url
*/
@Override
protected String accessTokenUrl(String code) {
return UrlBuilder.fromBaseUrl(source.accessToken())
.queryParam("code", code)
.queryParam("appid", config.getClientId())
.queryParam("secret", config.getClientSecret())
.queryParam("grant_type", "authorization_code")
.build();
}
/**
* 返回获取userInfo的url
*
* @param authToken
* @return 返回获取userInfo的url
*/
@Override
protected String userInfoUrl(AuthToken authToken) {
return UrlBuilder.fromBaseUrl(source.userInfo())
.queryParam("access_token", authToken.getAccessToken())
.queryParam("openid", authToken.getOpenId())
.queryParam("lang", "zh_CN")
.build();
}
/**
* 返回获取accessToken的url
*
* @param refreshToken
* @return 返回获取accessToken的url
*/
@Override
protected String refreshTokenUrl(String refreshToken) {
return UrlBuilder.fromBaseUrl(source.refresh())
.queryParam("appid", config.getClientId())
.queryParam("refresh_token", refreshToken)
.queryParam("grant_type", "refresh_token")
.build();
} }
} }
...@@ -10,10 +10,9 @@ import me.zhyd.oauth.model.AuthCallback; ...@@ -10,10 +10,9 @@ import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthToken; import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser; import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.model.AuthUserGender; import me.zhyd.oauth.model.AuthUserGender;
import me.zhyd.oauth.url.AuthWeiboUrlBuilder;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
import me.zhyd.oauth.utils.IpUtils; import me.zhyd.oauth.utils.IpUtils;
import me.zhyd.oauth.utils.StringUtils; import me.zhyd.oauth.utils.StringUtils;
import me.zhyd.oauth.utils.UrlBuilder;
/** /**
...@@ -26,24 +25,24 @@ import me.zhyd.oauth.utils.StringUtils; ...@@ -26,24 +25,24 @@ import me.zhyd.oauth.utils.StringUtils;
public class AuthWeiboRequest extends AuthDefaultRequest { public class AuthWeiboRequest extends AuthDefaultRequest {
public AuthWeiboRequest(AuthConfig config) { public AuthWeiboRequest(AuthConfig config) {
super(config, AuthSource.WEIBO, new AuthWeiboUrlBuilder()); super(config, AuthSource.WEIBO);
} }
@Override @Override
protected AuthToken getAccessToken(AuthCallback authCallback) { protected AuthToken getAccessToken(AuthCallback authCallback) {
String accessTokenUrl = this.urlBuilder.getAccessTokenUrl(authCallback.getCode()); HttpResponse response = doPostAuthorizationCode(authCallback.getCode());
HttpResponse response = HttpRequest.post(accessTokenUrl).execute();
String accessTokenStr = response.body(); String accessTokenStr = response.body();
JSONObject accessTokenObject = JSONObject.parseObject(accessTokenStr); JSONObject accessTokenObject = JSONObject.parseObject(accessTokenStr);
if (accessTokenObject.containsKey("error")) { if (accessTokenObject.containsKey("error")) {
throw new AuthException("Unable to get token from weibo using code [" + authCallback.getCode() + "]:" + accessTokenObject.getString("error_description")); throw new AuthException("Unable to get token from weibo using code [" + authCallback.getCode() + "]:" + accessTokenObject
.getString("error_description"));
} }
return AuthToken.builder() return AuthToken.builder()
.accessToken(accessTokenObject.getString("access_token")) .accessToken(accessTokenObject.getString("access_token"))
.uid(accessTokenObject.getString("uid")) .uid(accessTokenObject.getString("uid"))
.openId(accessTokenObject.getString("uid")) .openId(accessTokenObject.getString("uid"))
.expireIn(accessTokenObject.getIntValue("expires_in")) .expireIn(accessTokenObject.getIntValue("expires_in"))
.build(); .build();
} }
@Override @Override
...@@ -51,29 +50,41 @@ public class AuthWeiboRequest extends AuthDefaultRequest { ...@@ -51,29 +50,41 @@ public class AuthWeiboRequest extends AuthDefaultRequest {
String accessToken = authToken.getAccessToken(); String accessToken = authToken.getAccessToken();
String uid = authToken.getUid(); String uid = authToken.getUid();
String oauthParam = String.format("uid=%s&access_token=%s", uid, accessToken); String oauthParam = String.format("uid=%s&access_token=%s", uid, accessToken);
HttpResponse response = HttpRequest.get(this.urlBuilder.getUserInfoUrl(AuthUserInfoEntity.builder() HttpResponse response = HttpRequest.get(userInfoUrl(authToken))
.extra(oauthParam) .header("Authorization", "OAuth2 " + oauthParam)
.build())) .header("API-RemoteIP", IpUtils.getIp())
.header("Authorization", "OAuth2 " + oauthParam) .execute();
.header("API-RemoteIP", IpUtils.getIp())
.execute();
String userInfo = response.body(); String userInfo = response.body();
JSONObject object = JSONObject.parseObject(userInfo); JSONObject object = JSONObject.parseObject(userInfo);
if (object.containsKey("error")) { if (object.containsKey("error")) {
throw new AuthException(object.getString("error")); throw new AuthException(object.getString("error"));
} }
return AuthUser.builder() return AuthUser.builder()
.uuid(object.getString("id")) .uuid(object.getString("id"))
.username(object.getString("name")) .username(object.getString("name"))
.avatar(object.getString("profile_image_url")) .avatar(object.getString("profile_image_url"))
.blog(StringUtils.isEmpty(object.getString("url")) ? "https://weibo.com/" + object.getString("profile_url") : object .blog(StringUtils.isEmpty(object.getString("url")) ? "https://weibo.com/" + object.getString("profile_url") : object
.getString("url")) .getString("url"))
.nickname(object.getString("screen_name")) .nickname(object.getString("screen_name"))
.location(object.getString("location")) .location(object.getString("location"))
.remark(object.getString("description")) .remark(object.getString("description"))
.gender(AuthUserGender.getRealGender(object.getString("gender"))) .gender(AuthUserGender.getRealGender(object.getString("gender")))
.token(authToken) .token(authToken)
.source(AuthSource.WEIBO) .source(AuthSource.WEIBO)
.build(); .build();
}
/**
* 返回获取userInfo的url
*
* @param authToken
* @return 返回获取userInfo的url
*/
@Override
protected String userInfoUrl(AuthToken authToken) {
return UrlBuilder.fromBaseUrl(source.userInfo())
.queryParam("access_token", authToken.getAccessToken())
.queryParam("uid", authToken.getUid())
.build();
} }
} }
package me.zhyd.oauth.url;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthResponseStatus;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
import java.text.MessageFormat;
/**
* Baidu相关的URL构建类
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @version 1.0
* @since 1.8
*/
public class AuthAlipayUrlBuilder extends AuthDefaultUrlBuilder {
private static final String ALIPAY_AUTHORIZE_PATTERN = "{0}?app_id={1}&scope=auth_user&redirect_uri={2}&state={3}";
@Override
public String getAccessTokenUrl(String code) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
@Override
public String getUserInfoUrl(AuthUserInfoEntity userInfoEntity) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
@Override
public String getAuthorizeUrl() {
return MessageFormat.format(ALIPAY_AUTHORIZE_PATTERN, AuthSource.ALIPAY.authorize(), config.getClientId(), config.getRedirectUri(), this.getRealState(config.getState()));
}
@Override
public String getRefreshUrl(String refreshToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
@Override
public String getRevokeUrl(String accessToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
}
package me.zhyd.oauth.url;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthResponseStatus;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
import java.text.MessageFormat;
/**
* Baidu相关的URL构建类
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @version 1.0
* @since 1.8
*/
public class AuthBaiduUrlBuilder extends AuthDefaultUrlBuilder {
private static final String BAIDU_ACCESS_TOKEN_PATTERN = "{0}?client_id={1}&client_secret={2}&grant_type=authorization_code&code={3}&redirect_uri={4}";
private static final String BAIDU_USER_INFO_PATTERN = "{0}?access_token={1}";
private static final String BAIDU_AUTHORIZE_PATTERN = "{0}?client_id={1}&response_type=code&redirect_uri={2}&display=popup&state={3}";
private static final String BAIDU_REVOKE_PATTERN = "{0}?access_token={1}";
@Override
public String getAccessTokenUrl(String code) {
return MessageFormat.format(BAIDU_ACCESS_TOKEN_PATTERN, AuthSource.BAIDU.accessToken(), config.getClientId(), config.getClientSecret(), code, config.getRedirectUri());
}
@Override
public String getUserInfoUrl(AuthUserInfoEntity userInfoEntity) {
return MessageFormat.format(BAIDU_USER_INFO_PATTERN, AuthSource.BAIDU.userInfo(), userInfoEntity.getAccessToken());
}
@Override
public String getAuthorizeUrl() {
return MessageFormat.format(BAIDU_AUTHORIZE_PATTERN, AuthSource.BAIDU.authorize(), config.getClientId(), config.getRedirectUri(), this.getRealState(config.getState()));
}
@Override
public String getRefreshUrl(String refreshToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
@Override
public String getRevokeUrl(String accessToken) {
return MessageFormat.format(BAIDU_REVOKE_PATTERN, AuthSource.BAIDU.revoke(), accessToken);
}
}
package me.zhyd.oauth.url;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthResponseStatus;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
import java.text.MessageFormat;
/**
* Coding相关的URL构建类
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @version 1.0
* @since 1.8
*/
public class AuthCodingUrlBuilder extends AuthDefaultUrlBuilder {
private static final String CODING_ACCESS_TOKEN_PATTERN = "{0}?client_id={1}&client_secret={2}&grant_type=authorization_code&code={3}";
private static final String CODING_USER_INFO_PATTERN = "{0}?access_token={1}";
private static final String CODING_AUTHORIZE_PATTERN = "{0}?client_id={1}&response_type=code&redirect_uri={2}&scope=user&state={3}";
@Override
public String getAccessTokenUrl(String code) {
return MessageFormat.format(CODING_ACCESS_TOKEN_PATTERN, AuthSource.CODING.accessToken(), config.getClientId(), config.getClientSecret(), code);
}
@Override
public String getUserInfoUrl(AuthUserInfoEntity userInfoEntity) {
return MessageFormat.format(CODING_USER_INFO_PATTERN, AuthSource.CODING.userInfo(), userInfoEntity.getAccessToken());
}
@Override
public String getAuthorizeUrl() {
return MessageFormat.format(CODING_AUTHORIZE_PATTERN, AuthSource.CODING.authorize(), config.getClientId(), config.getRedirectUri(), this.getRealState(config.getState()));
}
@Override
public String getRefreshUrl(String refreshToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
@Override
public String getRevokeUrl(String accessToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
}
package me.zhyd.oauth.url;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthResponseStatus;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
import java.text.MessageFormat;
/**
* csdn相关的URL构建类
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @version 1.0
* @since 1.8
*/
@Deprecated
public class AuthCsdnUrlBuilder extends AuthDefaultUrlBuilder {
private static final String CSDN_ACCESS_TOKEN_PATTERN = "{0}?client_id={1}&client_secret={2}&grant_type=authorization_code&code={3}&redirect_uri={4}";
private static final String CSDN_USER_INFO_PATTERN = "{0}?access_token={1}";
private static final String CSDN_AUTHORIZE_PATTERN = "{0}?client_id={1}&response_type=code&redirect_uri={2}&state={3}";
@Override
public String getAccessTokenUrl(String code) {
return MessageFormat.format(CSDN_ACCESS_TOKEN_PATTERN, AuthSource.CSDN.accessToken(), config.getClientId(), config.getClientSecret(), code, config.getRedirectUri());
}
@Override
public String getUserInfoUrl(AuthUserInfoEntity userInfoEntity) {
return MessageFormat.format(CSDN_USER_INFO_PATTERN, AuthSource.CSDN.userInfo(), userInfoEntity.getAccessToken());
}
@Override
public String getAuthorizeUrl() {
return MessageFormat.format(CSDN_AUTHORIZE_PATTERN, AuthSource.CSDN.authorize(), config.getClientId(), config.getRedirectUri(), this.getRealState(config.getState()));
}
@Override
public String getRefreshUrl(String refreshToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
@Override
public String getRevokeUrl(String accessToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
}
package me.zhyd.oauth.url;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthResponseStatus;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
import me.zhyd.oauth.utils.StringUtils;
/**
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @version 1.0
* @since 1.8
*/
public abstract class AuthDefaultUrlBuilder {
protected AuthConfig config;
/**
* 获取AccessToken的URL
*
* @param code 第三方平台返回的code
* @return AccessTokenUrl
*/
public abstract String getAccessTokenUrl(String code);
/**
* 获取用户信息的URL
*
* @param userInfoEntity 传递生成 UserInfoUrl 必须的参数
* @return UserInfoUrl
*/
public abstract String getUserInfoUrl(AuthUserInfoEntity userInfoEntity);
/**
* 获取跳转授权页面的URL
*
* @return AuthorizeUrl
*/
public abstract String getAuthorizeUrl();
/**
* 获取刷新token的URL
*
* @param refreshToken 授权后取得的refresh token
* @return RefreshUrl
*/
public abstract String getRefreshUrl(String refreshToken);
/**
* 获取取消授权的URL
*
* @param accessToken 授权后的token
* @return RevokeUrl
*/
public abstract String getRevokeUrl(String accessToken);
/**
* 获取openId的地址,目前只有qq平台需要,故不需要子类强制重写
*
* @param accessToken 用户授权后返回的accesstoken
* @param unionid 是否需要申请unionid,目前只针对qq登录
* 注:qq授权登录时,获取unionid需要单独发送邮件申请权限。如果个人开发者账号中申请了该权限,可以将该值置为true,在获取openId时就会同步获取unionId
* 参考链接:http://wiki.connect.qq.com/unionid%E4%BB%8B%E7%BB%8D
* @return openIdUrl
*/
public String getOpenIdUrl(String accessToken, boolean unionid) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
/**
* 获取state,如果为空, 则默认去当前日期的时间戳
*
* @param state 原始的state
* @return 返回不为null的state
*/
protected String getRealState(String state) {
return StringUtils.isEmpty(state) ? String.valueOf(System.currentTimeMillis()) : state;
}
public void setAuthConfig(AuthConfig config) {
this.config = config;
}
}
package me.zhyd.oauth.url;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthResponseStatus;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
import java.text.MessageFormat;
/**
* 钉钉相关的URL构建类
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @version 1.0
* @since 1.8
*/
public class AuthDingtalkUrlBuilder extends AuthDefaultUrlBuilder {
private static final String DING_TALK_QRCONNECT_PATTERN = "{0}?appid={1}&response_type=code&scope=snsapi_login&redirect_uri={2}&state={3}";
private static final String DING_TALK_USER_INFO_PATTERN = "{0}?signature={1}&timestamp={2}&accessKey={3}";
@Override
public String getAccessTokenUrl(String code) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
@Override
public String getUserInfoUrl(AuthUserInfoEntity userInfoEntity) {
return MessageFormat.format(DING_TALK_USER_INFO_PATTERN, AuthSource.DINGTALK.userInfo(), userInfoEntity.getSignature(), userInfoEntity.getTimestamp(), userInfoEntity.getClientId());
}
@Override
public String getAuthorizeUrl() {
return MessageFormat.format(DING_TALK_QRCONNECT_PATTERN, AuthSource.DINGTALK.authorize(), config.getClientId(), config.getRedirectUri(), this.getRealState(config.getState()));
}
@Override
public String getRefreshUrl(String refreshToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
@Override
public String getRevokeUrl(String accessToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
}
package me.zhyd.oauth.url;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthResponseStatus;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
import java.text.MessageFormat;
/**
* 抖音相关的URL构建类
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @version 1.0
* @since 1.8
*/
public class AuthDouyinUrlBuilder extends AuthDefaultUrlBuilder {
private static final String DOUYIN_AUTHORIZE_PATTERN = "{0}?client_key={1}&redirect_uri={2}&state={3}&response_type=code&scope=user_info";
private static final String DOUYIN_ACCESS_TOKEN_PATTERN = "{0}?client_key={1}&client_secret={2}&code={3}&grant_type=authorization_code";
private static final String DOUYIN_USER_INFO_PATTERN = "{0}?access_token={1}&open_id={2}";
private static final String DOUYIN_REFRESH_TOKEN_PATTERN = "{0}?client_key={1}&refresh_token={2}&grant_type=refresh_token";
@Override
public String getAccessTokenUrl(String code) {
return MessageFormat.format(DOUYIN_ACCESS_TOKEN_PATTERN, AuthSource.DOUYIN.accessToken(), config.getClientId(), config.getClientSecret(), code);
}
@Override
public String getUserInfoUrl(AuthUserInfoEntity userInfoEntity) {
return MessageFormat.format(DOUYIN_USER_INFO_PATTERN, AuthSource.DOUYIN.userInfo(), userInfoEntity.getAccessToken(), userInfoEntity.getOpenId());
}
@Override
public String getAuthorizeUrl() {
return MessageFormat.format(DOUYIN_AUTHORIZE_PATTERN, AuthSource.DOUYIN.authorize(), config.getClientId(), config.getRedirectUri(), this.getRealState(config.getState()));
}
@Override
public String getRefreshUrl(String refreshToken) {
return MessageFormat.format(DOUYIN_REFRESH_TOKEN_PATTERN, AuthSource.DOUYIN.refresh(), config.getClientId(), refreshToken);
}
@Override
public String getRevokeUrl(String accessToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
}
package me.zhyd.oauth.url;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthResponseStatus;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
import java.text.MessageFormat;
/**
* Facebook相关的URL构建类
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @version 1.0
* @since 1.8
*/
public class AuthFacebookUrlBuilder extends AuthDefaultUrlBuilder {
private static final String FACEBOOK_AUTHORIZE_PATTERN = "{0}?client_id={1}&redirect_uri={2}&state={3}&response_type=code&scope=";
private static final String FACEBOOK_ACCESS_TOKEN_PATTERN = "{0}?client_id={1}&client_secret={2}&code={3}&redirect_uri={4}&grant_type=authorization_code";
private static final String FACEBOOK_USER_INFO_PATTERN = "{0}?access_token={1}&fields=id,name,birthday,gender,hometown,email,devices,picture.width(400)";
@Override
public String getAccessTokenUrl(String code) {
return MessageFormat.format(FACEBOOK_ACCESS_TOKEN_PATTERN, AuthSource.FACEBOOK.accessToken(), config.getClientId(), config.getClientSecret(), code, config.getRedirectUri());
}
@Override
public String getUserInfoUrl(AuthUserInfoEntity userInfoEntity) {
return MessageFormat.format(FACEBOOK_USER_INFO_PATTERN, AuthSource.FACEBOOK.userInfo(), userInfoEntity.getAccessToken());
}
@Override
public String getAuthorizeUrl() {
return MessageFormat.format(FACEBOOK_AUTHORIZE_PATTERN, AuthSource.FACEBOOK.authorize(), config.getClientId(), config.getRedirectUri(), this.getRealState(config.getState()));
}
@Override
public String getRefreshUrl(String refreshToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
@Override
public String getRevokeUrl(String accessToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
}
package me.zhyd.oauth.url;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthResponseStatus;
import me.zhyd.oauth.url.entity.*;
import java.text.MessageFormat;
/**
* Gitee相关的URL构建类
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @version 1.0
* @since 1.8
*/
public class AuthGiteeUrlBuilder extends AuthDefaultUrlBuilder {
private static final String GITEE_ACCESS_TOKEN_PATTERN = "{0}?client_id={1}&client_secret={2}&grant_type=authorization_code&code={3}&redirect_uri={4}";
private static final String GITEE_USER_INFO_PATTERN = "{0}?access_token={1}";
private static final String GITEE_AUTHORIZE_PATTERN = "{0}?client_id={1}&response_type=code&redirect_uri={2}&state={3}";
@Override
public String getAccessTokenUrl(String code) {
return MessageFormat.format(GITEE_ACCESS_TOKEN_PATTERN, AuthSource.GITEE.accessToken(), config.getClientId(), config.getClientSecret(), code, config.getRedirectUri());
}
@Override
public String getUserInfoUrl(AuthUserInfoEntity userInfoEntity) {
return MessageFormat.format(GITEE_USER_INFO_PATTERN, AuthSource.GITEE.userInfo(), userInfoEntity.getAccessToken());
}
@Override
public String getAuthorizeUrl() {
return MessageFormat.format(GITEE_AUTHORIZE_PATTERN, AuthSource.GITEE.authorize(), config.getClientId(), config.getRedirectUri(), this.getRealState(config.getState()));
}
@Override
public String getRefreshUrl(String refreshToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
@Override
public String getRevokeUrl(String accessToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
}
package me.zhyd.oauth.url;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthResponseStatus;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
import java.text.MessageFormat;
/**
* Github相关的URL构建类
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @version 1.0
* @since 1.8
*/
public class AuthGithubUrlBuilder extends AuthDefaultUrlBuilder {
private static final String GITHUB_ACCESS_TOKEN_PATTERN = "{0}?client_id={1}&client_secret={2}&code={3}&redirect_uri={4}";
private static final String GITHUB_USER_INFO_PATTERN = "{0}?access_token={1}";
private static final String GITHUB_AUTHORIZE_PATTERN = "{0}?client_id={1}&redirect_uri={2}&state={3}";
@Override
public String getAccessTokenUrl(String code) {
return MessageFormat.format(GITHUB_ACCESS_TOKEN_PATTERN, AuthSource.GITHUB.accessToken(), config.getClientId(), config.getClientSecret(), code, config.getRedirectUri());
}
@Override
public String getUserInfoUrl(AuthUserInfoEntity userInfoEntity) {
return MessageFormat.format(GITHUB_USER_INFO_PATTERN, AuthSource.GITHUB.userInfo(), userInfoEntity.getAccessToken());
}
@Override
public String getAuthorizeUrl() {
return MessageFormat.format(GITHUB_AUTHORIZE_PATTERN, AuthSource.GITHUB.authorize(), config.getClientId(), config.getRedirectUri(), this.getRealState(config.getState()));
}
@Override
public String getRefreshUrl(String refreshToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
@Override
public String getRevokeUrl(String accessToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
}
package me.zhyd.oauth.url;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthResponseStatus;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
import java.text.MessageFormat;
/**
* Google相关的URL构建类
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @version 1.0
* @since 1.8
*/
public class AuthGoogleUrlBuilder extends AuthDefaultUrlBuilder {
private static final String GOOGLE_AUTHORIZE_PATTERN = "{0}?client_id={1}&response_type=code&scope=openid%20email%20profile&redirect_uri={2}&state={3}";
private static final String GOOGLE_ACCESS_TOKEN_PATTERN = "{0}?client_id={1}&client_secret={2}&code={3}&redirect_uri={4}&grant_type=authorization_code";
private static final String GOOGLE_USER_INFO_PATTERN = "{0}?id_token={1}";
@Override
public String getAccessTokenUrl(String code) {
return MessageFormat.format(GOOGLE_ACCESS_TOKEN_PATTERN, AuthSource.GOOGLE.accessToken(), config.getClientId(), config.getClientSecret(), code, config.getRedirectUri());
}
@Override
public String getUserInfoUrl(AuthUserInfoEntity userInfoEntity) {
return MessageFormat.format(GOOGLE_USER_INFO_PATTERN, AuthSource.GOOGLE.userInfo(), userInfoEntity.getAccessToken());
}
@Override
public String getAuthorizeUrl() {
return MessageFormat.format(GOOGLE_AUTHORIZE_PATTERN, AuthSource.GOOGLE.authorize(), config.getClientId(), config.getRedirectUri(), this.getRealState(config.getState()));
}
@Override
public String getRefreshUrl(String refreshToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
@Override
public String getRevokeUrl(String accessToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
}
package me.zhyd.oauth.url;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthResponseStatus;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
import java.text.MessageFormat;
/**
* Microsoft相关的URL构建类
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @version 1.0
* @since 1.8
*/
public class AuthLinkedinUrlBuilder extends AuthDefaultUrlBuilder {
private static final String LINKEDIN_AUTHORIZE_PATTERN = "{0}?client_id={1}&redirect_uri={2}&state={3}&response_type=code&scope=r_liteprofile%20r_emailaddress%20w_member_social";
private static final String LINKEDIN_ACCESS_TOKEN_PATTERN = "{0}?client_id={1}&client_secret={2}&code={3}&redirect_uri={4}&grant_type=authorization_code";
private static final String LINKEDIN_USER_INFO_PATTERN = "{0}?projection=(id,firstName,lastName,profilePicture(displayImage~:playableStreams))";
private static final String LINKEDIN_REFRESH_TOKEN_PATTERN = "{0}?client_id={1}&client_secret={2}&refresh_token={3}&grant_type=refresh_token";
@Override
public String getAccessTokenUrl(String code) {
return MessageFormat.format(LINKEDIN_ACCESS_TOKEN_PATTERN, AuthSource.LINKEDIN.accessToken(), config.getClientId(), config.getClientSecret(), code, config.getRedirectUri());
}
@Override
public String getUserInfoUrl(AuthUserInfoEntity userInfoEntity) {
return MessageFormat.format(LINKEDIN_USER_INFO_PATTERN, AuthSource.LINKEDIN.userInfo());
}
@Override
public String getAuthorizeUrl() {
return MessageFormat.format(LINKEDIN_AUTHORIZE_PATTERN, AuthSource.LINKEDIN.authorize(), config.getClientId(), config.getRedirectUri(), this.getRealState(config.getState()));
}
@Override
public String getRefreshUrl(String refreshToken) {
return MessageFormat.format(LINKEDIN_REFRESH_TOKEN_PATTERN, AuthSource.LINKEDIN.refresh(), config.getClientId(), config.getClientSecret(), refreshToken);
}
@Override
public String getRevokeUrl(String accessToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
}
package me.zhyd.oauth.url;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthResponseStatus;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
import java.text.MessageFormat;
/**
* 小米相关的URL构建类
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @version 1.0
* @since 1.8
*/
public class AuthMiUrlBuilder extends AuthDefaultUrlBuilder {
private static final String MI_AUTHORIZE_PATTERN = "{0}?client_id={1}&redirect_uri={2}&response_type=code&scope=user/profile%20user/openIdV2%20user/phoneAndEmail&state={3}&skip_confirm=false";
private static final String MI_ACCESS_TOKEN_PATTERN = "{0}?client_id={1}&client_secret={2}&redirect_uri={3}&code={4}&grant_type=authorization_code";
private static final String MI_USER_INFO_PATTERN = "{0}?clientId={1}&token={2}";
private static final String MI_REFRESH_TOKEN_PATTERN = "{0}?client_id={1}&client_secret={2}&redirect_uri={3}&refresh_token={4}&grant_type=refresh_token";
@Override
public String getAccessTokenUrl(String code) {
return MessageFormat.format(MI_ACCESS_TOKEN_PATTERN, AuthSource.MI.accessToken(), config.getClientId(), config.getClientSecret(), config.getRedirectUri(), code);
}
@Override
public String getUserInfoUrl(AuthUserInfoEntity userInfoEntity) {
return MessageFormat.format(MI_USER_INFO_PATTERN, AuthSource.MI.userInfo(), userInfoEntity.getClientId(), userInfoEntity.getAccessToken());
}
@Override
public String getAuthorizeUrl() {
return MessageFormat.format(MI_AUTHORIZE_PATTERN, AuthSource.MI.authorize(), config.getClientId(), config.getRedirectUri(), this.getRealState(config.getState()));
}
@Override
public String getRefreshUrl(String refreshToken) {
return MessageFormat.format(MI_REFRESH_TOKEN_PATTERN, AuthSource.MI.refresh(), config.getClientId(), config.getClientSecret(), config.getRedirectUri(), refreshToken);
}
@Override
public String getRevokeUrl(String accessToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
}
package me.zhyd.oauth.url;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthResponseStatus;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
import java.text.MessageFormat;
/**
* Microsoft相关的URL构建类
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @version 1.0
* @since 1.8
*/
public class AuthMicrosoftUrlBuilder extends AuthDefaultUrlBuilder {
private static final String MICROSOFT_AUTHORIZE_PATTERN = "{0}?client_id={1}&response_type=code&redirect_uri={2}&response_mode=query&scope=offline_access%20user.read%20mail.read&state={3}";
private static final String MICROSOFT_ACCESS_TOKEN_PATTERN = "{0}?client_id={1}&client_secret={2}&scope=user.read%20mail.read&redirect_uri={3}&code={4}&grant_type=authorization_code";
private static final String MICROSOFT_USER_INFO_PATTERN = "{0}";
private static final String MICROSOFT_REFRESH_TOKEN_PATTERN = "{0}?client_id={1}&client_secret={2}&scope=user.read%20mail.read&redirect_uri={3}&refresh_token={4}&grant_type=refresh_token";
@Override
public String getAccessTokenUrl(String code) {
return MessageFormat.format(MICROSOFT_ACCESS_TOKEN_PATTERN, AuthSource.MICROSOFT.accessToken(), config.getClientId(), config.getClientSecret(), config.getRedirectUri(), code);
}
@Override
public String getUserInfoUrl(AuthUserInfoEntity userInfoEntity) {
return MessageFormat.format(MICROSOFT_USER_INFO_PATTERN, AuthSource.MICROSOFT.userInfo());
}
@Override
public String getAuthorizeUrl() {
return MessageFormat.format(MICROSOFT_AUTHORIZE_PATTERN, AuthSource.MICROSOFT.authorize(), config.getClientId(), config.getRedirectUri(), this.getRealState(config.getState()));
}
@Override
public String getRefreshUrl(String refreshToken) {
return MessageFormat.format(MICROSOFT_REFRESH_TOKEN_PATTERN, AuthSource.MICROSOFT.refresh(), config.getClientId(), config.getClientSecret(), config.getRedirectUri(), refreshToken);
}
@Override
public String getRevokeUrl(String accessToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
}
package me.zhyd.oauth.url;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthResponseStatus;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
import java.text.MessageFormat;
/**
* OSChina相关的URL构建类
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @version 1.0
* @since 1.8
*/
public class AuthOschinaUrlBuilder extends AuthDefaultUrlBuilder {
private static final String OSCHINA_ACCESS_TOKEN_PATTERN = "{0}?client_id={1}&client_secret={2}&grant_type=authorization_code&code={3}&redirect_uri={4}&dataType=json";
private static final String OSCHINA_USER_INFO_PATTERN = "{0}?access_token={1}&dataType=json";
private static final String OSCHINA_AUTHORIZE_PATTERN = "{0}?client_id={1}&response_type=code&redirect_uri={2}&state={3}";
@Override
public String getAccessTokenUrl(String code) {
return MessageFormat.format(OSCHINA_ACCESS_TOKEN_PATTERN, AuthSource.OSCHINA.accessToken(), config.getClientId(), config.getClientSecret(), code, config.getRedirectUri());
}
@Override
public String getUserInfoUrl(AuthUserInfoEntity userInfoEntity) {
return MessageFormat.format(OSCHINA_USER_INFO_PATTERN, AuthSource.OSCHINA.userInfo(), userInfoEntity.getAccessToken());
}
@Override
public String getAuthorizeUrl() {
return MessageFormat.format(OSCHINA_AUTHORIZE_PATTERN, AuthSource.OSCHINA.authorize(), config.getClientId(), config.getRedirectUri(), this.getRealState(config.getState()));
}
@Override
public String getRefreshUrl(String refreshToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
@Override
public String getRevokeUrl(String accessToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
}
package me.zhyd.oauth.url;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthResponseStatus;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
import java.text.MessageFormat;
/**
* QQ相关的URL构建类
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @version 1.0
* @since 1.8
*/
public class AuthQqUrlBuilder extends AuthDefaultUrlBuilder {
private static final String QQ_ACCESS_TOKEN_PATTERN = "{0}?client_id={1}&client_secret={2}&grant_type=authorization_code&code={3}&redirect_uri={4}";
private static final String QQ_USER_INFO_PATTERN = "{0}?oauth_consumer_key={1}&access_token={2}&openid={3}";
private static final String QQ_AUTHORIZE_PATTERN = "{0}?client_id={1}&response_type=code&redirect_uri={2}&state={3}";
private static final String QQ_OPENID_PATTERN = "{0}?access_token={1}&unionid={2}";
@Override
public String getAccessTokenUrl(String code) {
return MessageFormat.format(QQ_ACCESS_TOKEN_PATTERN, AuthSource.QQ.accessToken(), config.getClientId(), config.getClientSecret(), code, config.getRedirectUri());
}
@Override
public String getUserInfoUrl(AuthUserInfoEntity userInfoEntity) {
return MessageFormat.format(QQ_USER_INFO_PATTERN, AuthSource.QQ.userInfo(), userInfoEntity.getClientId(), userInfoEntity.getAccessToken(), userInfoEntity.getOpenId());
}
@Override
public String getAuthorizeUrl() {
return MessageFormat.format(QQ_AUTHORIZE_PATTERN, AuthSource.QQ.authorize(), config.getClientId(), config.getRedirectUri(), this.getRealState(config.getState()));
}
@Override
public String getRefreshUrl(String refreshToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
@Override
public String getRevokeUrl(String accessToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
@Override
public String getOpenIdUrl(String accessToken, boolean unionid) {
return MessageFormat.format(QQ_OPENID_PATTERN, "https://graph.qq.com/oauth2.0/me", accessToken, unionid ? 1 : 0);
}
}
package me.zhyd.oauth.url;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthResponseStatus;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
import java.text.MessageFormat;
import static me.zhyd.oauth.config.AuthSource.RENREN;
/**
* 人人网相关的URL构建类
*
* @author hongwei.peng (pengisgood(at)gmail(dot)com)
* @version 1.8.1
* @since 1.8.1
*/
public class AuthRenrenUrlBuilder extends AuthDefaultUrlBuilder {
private static final String RENREN_ACCESS_TOKEN_PATTERN = "{0}?client_id={1}&client_secret={2}&grant_type=authorization_code&code={3}&redirect_uri={4}";
private static final String RENREN_USER_INFO_PATTERN = "{0}?access_token={1}&userId={2}";
private static final String RENREN_AUTHORIZE_PATTERN = "{0}?client_id={1}&response_type=code&redirect_uri={2}&state={3}";
private static final String RENREN_REFRESH_PATTERN = "{0}?refresh_token={1}&client_id={2}&client_secret={3}&grant_type=refresh_token";
@Override
public String getAccessTokenUrl(String code) {
return MessageFormat.format(RENREN_ACCESS_TOKEN_PATTERN, RENREN.accessToken(), config.getClientId(), config.getClientSecret(), code, config.getRedirectUri());
}
@Override
public String getUserInfoUrl(AuthUserInfoEntity userInfoEntity) {
return MessageFormat.format(RENREN_USER_INFO_PATTERN, RENREN.userInfo(), userInfoEntity.getAccessToken(), userInfoEntity.getOpenId());
}
@Override
public String getAuthorizeUrl() {
return MessageFormat.format(RENREN_AUTHORIZE_PATTERN, RENREN.authorize(), config.getClientId(), config.getRedirectUri(), this.getRealState(config.getState()));
}
@Override
public String getRefreshUrl(String refreshToken) {
return MessageFormat.format(RENREN_REFRESH_PATTERN, RENREN.refresh(), refreshToken, config.getClientId(), config.getClientSecret());
}
@Override
public String getRevokeUrl(String accessToken) {
throw new AuthException(AuthResponseStatus.UNSUPPORTED);
}
}
package me.zhyd.oauth.url;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthResponseStatus;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
import java.text.MessageFormat;
/**
* 淘宝相关的URL构建类
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @version 1.0
* @since 1.8
*/
public class AuthTaobaoUrlBuilder extends AuthDefaultUrlBuilder {
private static final String TAOBAO_AUTHORIZE_PATTERN = "{0}?response_type=code&client_id={1}&redirect_uri={2}&state={3}&view=web";
private static final String TAOBAO_ACCESS_TOKEN_PATTERN = "{0}?client_id={1}&client_secret={2}&code={3}&redirect_uri={4}&grant_type=authorization_code";
@Override
public String getAccessTokenUrl(String code) {
return MessageFormat.format(TAOBAO_ACCESS_TOKEN_PATTERN, AuthSource.TAOBAO.accessToken(), config.getClientId(), config.getClientSecret(), code, config.getRedirectUri());
}
@Override
public String getUserInfoUrl(AuthUserInfoEntity userInfoEntity) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
@Override
public String getAuthorizeUrl() {
return MessageFormat.format(TAOBAO_AUTHORIZE_PATTERN, AuthSource.TAOBAO.authorize(), config.getClientId(), config.getRedirectUri(), this.getRealState(config.getState()));
}
@Override
public String getRefreshUrl(String refreshToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
@Override
public String getRevokeUrl(String accessToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
}
package me.zhyd.oauth.url;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
import java.text.MessageFormat;
/**
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @version 1.0
* @website https://www.zhyd.me
* @date 2019/7/16 22:22
* @since 1.8
*/
public class AuthTeambitionUrlBuilder extends AuthDefaultUrlBuilder {
private static final String TEAMBITION_AUTHORIZE_PATTERN = "{0}?client_id={1}&redirect_uri={2}&state={3}&response_type=code";
@Override
public String getAccessTokenUrl(String code) {
return AuthSource.TEAMBITION.accessToken();
}
@Override
public String getUserInfoUrl(AuthUserInfoEntity userInfoEntity) {
return AuthSource.TEAMBITION.userInfo();
}
@Override
public String getAuthorizeUrl() {
return MessageFormat.format(TEAMBITION_AUTHORIZE_PATTERN, AuthSource.TEAMBITION.authorize(), config.getClientId(), config.getRedirectUri(), this.getRealState(config.getState()));
}
@Override
public String getRefreshUrl(String refreshToken) {
return AuthSource.TEAMBITION.refresh();
}
@Override
public String getRevokeUrl(String accessToken) {
return null;
}
}
package me.zhyd.oauth.url;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthResponseStatus;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
import java.text.MessageFormat;
/**
* 今日头条相关的URL构建类
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @version 1.0
* @since 1.8
*/
public class AuthTencentCloudUrlBuilder extends AuthDefaultUrlBuilder {
private static final String TENCENT_ACCESS_TOKEN_PATTERN = "{0}?client_id={1}&client_secret={2}&grant_type=authorization_code&code={3}";
private static final String TENCENT_USER_INFO_PATTERN = "{0}?access_token={1}";
private static final String TENCENT_AUTHORIZE_PATTERN = "{0}?client_id={1}&response_type=code&redirect_uri={2}&scope=user&state={3}";
@Override
public String getAccessTokenUrl(String code) {
return MessageFormat.format(TENCENT_ACCESS_TOKEN_PATTERN, AuthSource.TENCENT_CLOUD.accessToken(), config.getClientId(), config.getClientSecret(), code);
}
@Override
public String getUserInfoUrl(AuthUserInfoEntity userInfoEntity) {
return MessageFormat.format(TENCENT_USER_INFO_PATTERN, AuthSource.TENCENT_CLOUD.userInfo(), userInfoEntity.getAccessToken());
}
@Override
public String getAuthorizeUrl() {
return MessageFormat.format(TENCENT_AUTHORIZE_PATTERN, AuthSource.TENCENT_CLOUD.authorize(), config.getClientId(), config.getRedirectUri(), this.getRealState(config.getState()));
}
@Override
public String getRefreshUrl(String refreshToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
@Override
public String getRevokeUrl(String accessToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
}
package me.zhyd.oauth.url;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthResponseStatus;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
import java.text.MessageFormat;
/**
* 今日头条相关的URL构建类
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @version 1.0
* @since 1.8
*/
public class AuthToutiaoUrlBuilder extends AuthDefaultUrlBuilder {
private static final String TOUTIAO_ACCESS_TOKEN_PATTERN = "{0}?client_key={1}&client_secret={2}&code={3}&grant_type=authorize_code";
private static final String TOUTIAO_USER_INFO_PATTERN = "{0}?client_key={1}&access_token={2}";
private static final String TOUTIAO_AUTHORIZE_PATTERN = "{0}?client_key={1}&redirect_uri={2}&state={3}&response_type=code&auth_only=1&display=0";
@Override
public String getAccessTokenUrl(String code) {
return MessageFormat.format(TOUTIAO_ACCESS_TOKEN_PATTERN, AuthSource.TOUTIAO.accessToken(), config.getClientId(), config.getClientSecret(), code);
}
@Override
public String getUserInfoUrl(AuthUserInfoEntity userInfoEntity) {
return MessageFormat.format(TOUTIAO_USER_INFO_PATTERN, AuthSource.TOUTIAO.userInfo(), userInfoEntity.getClientId(), userInfoEntity.getAccessToken());
}
@Override
public String getAuthorizeUrl() {
return MessageFormat.format(TOUTIAO_AUTHORIZE_PATTERN, AuthSource.TOUTIAO.authorize(), config.getClientId(), config.getRedirectUri(), this.getRealState(config.getState()));
}
@Override
public String getRefreshUrl(String refreshToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
@Override
public String getRevokeUrl(String accessToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
}
package me.zhyd.oauth.url;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthResponseStatus;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
import java.text.MessageFormat;
/**
* 微信相关的URL构建类
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @version 1.0
* @since 1.8
*/
public class AuthWechatUrlBuilder extends AuthDefaultUrlBuilder {
private static final String WECHAT_AUTHORIZE_PATTERN = "{0}?appid={1}&redirect_uri={2}&response_type=code&scope=snsapi_login&state={3}#wechat_redirect";
private static final String WECHAT_ACCESS_TOKEN_PATTERN = "{0}?appid={1}&secret={2}&code={3}&grant_type=authorization_code";
private static final String WECHAT_REFRESH_TOKEN_PATTERN = "{0}?appid={1}&grant_type=refresh_token&refresh_token={2}";
private static final String WECHAT_USER_INFO_PATTERN = "{0}?access_token={1}&openid={2}&lang=zh_CN";
@Override
public String getAccessTokenUrl(String code) {
return MessageFormat.format(WECHAT_ACCESS_TOKEN_PATTERN, AuthSource.WECHAT.accessToken(), config.getClientId(), config.getClientSecret(), code);
}
@Override
public String getUserInfoUrl(AuthUserInfoEntity userInfoEntity) {
return MessageFormat.format(WECHAT_USER_INFO_PATTERN, AuthSource.WECHAT.userInfo(), userInfoEntity.getAccessToken(), userInfoEntity.getOpenId());
}
@Override
public String getAuthorizeUrl() {
return MessageFormat.format(WECHAT_AUTHORIZE_PATTERN, AuthSource.WECHAT.authorize(), config.getClientId(), config.getRedirectUri(), this.getRealState(config.getState()));
}
@Override
public String getRefreshUrl(String refreshToken) {
return MessageFormat.format(WECHAT_REFRESH_TOKEN_PATTERN, AuthSource.WECHAT.refresh(), config.getClientId(), refreshToken);
}
@Override
public String getRevokeUrl(String accessToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
}
package me.zhyd.oauth.url;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthResponseStatus;
import me.zhyd.oauth.url.entity.AuthUserInfoEntity;
import java.text.MessageFormat;
/**
* 微博相关的URL构建类
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @version 1.0
* @since 1.8
*/
public class AuthWeiboUrlBuilder extends AuthDefaultUrlBuilder {
private static final String WEIBO_ACCESS_TOKEN_PATTERN = "{0}?client_id={1}&client_secret={2}&grant_type=authorization_code&code={3}&redirect_uri={4}";
private static final String WEIBO_USER_INFO_PATTERN = "{0}?{1}";
private static final String WEIBO_AUTHORIZE_PATTERN = "{0}?client_id={1}&response_type=code&redirect_uri={2}&state={3}";
@Override
public String getAccessTokenUrl(String code) {
return MessageFormat.format(WEIBO_ACCESS_TOKEN_PATTERN, AuthSource.WEIBO.accessToken(), config.getClientId(), config.getClientSecret(), code, config.getRedirectUri());
}
@Override
public String getUserInfoUrl(AuthUserInfoEntity userInfoEntity) {
return MessageFormat.format(WEIBO_USER_INFO_PATTERN, AuthSource.WEIBO.userInfo(), userInfoEntity.getExtra());
}
@Override
public String getAuthorizeUrl() {
return MessageFormat.format(WEIBO_AUTHORIZE_PATTERN, AuthSource.WEIBO.authorize(), config.getClientId(), config.getRedirectUri(), this.getRealState(config.getState()));
}
@Override
public String getRefreshUrl(String refreshToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
@Override
public String getRevokeUrl(String accessToken) {
throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED);
}
}
package me.zhyd.oauth.url.entity;
import lombok.Builder;
import lombok.Getter;
/**
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @version 1.0
* @since 1.8
*/
@Getter
@Builder
public class AuthUserInfoEntity {
/**
* 授权返回的token
*/
private String accessToken;
/**
* 用户openId
*/
private String openId;
/**
* client key
*/
private String clientId;
/**
* 额外的属性
*/
private String extra;
/**
* 额外的属性
*/
private String signature;
/**
* 额外的属性
*/
private String timestamp;
}
package me.zhyd.oauth.utils; package me.zhyd.oauth.utils;
import cn.hutool.core.lang.Assert; import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import lombok.Data; import lombok.Data;
...@@ -12,7 +13,7 @@ import java.util.Map; ...@@ -12,7 +13,7 @@ import java.util.Map;
* 构造URL * 构造URL
* </p> * </p>
* *
* @author yangkai.shen * @author yangkai.shen (https://xkcoding.com)
* @date Created in 2019-07-18 15:47 * @date Created in 2019-07-18 15:47
*/ */
@Data @Data
...@@ -63,6 +64,9 @@ public class UrlBuilder { ...@@ -63,6 +64,9 @@ public class UrlBuilder {
* @return url * @return url
*/ */
public String build(boolean encode) { public String build(boolean encode) {
if (MapUtil.isEmpty(this.params)) {
return this.baseUrl;
}
String baseUrl = StrUtil.addSuffixIfNot(this.baseUrl, "?"); String baseUrl = StrUtil.addSuffixIfNot(this.baseUrl, "?");
String paramString = GlobalAuthUtil.parseMapToString(this.params, encode); String paramString = GlobalAuthUtil.parseMapToString(this.params, encode);
return baseUrl + paramString; return baseUrl + paramString;
......
...@@ -11,7 +11,7 @@ import org.junit.Test; ...@@ -11,7 +11,7 @@ import org.junit.Test;
* UrlBuilder测试类 * UrlBuilder测试类
* </p> * </p>
* *
* @author yangkai.shen * @author yangkai.shen (https://xkcoding.com)
* @date Created in 2019-07-18 16:36 * @date Created in 2019-07-18 16:36
*/ */
public class UrlBuilderTest { public class UrlBuilderTest {
...@@ -22,15 +22,13 @@ public class UrlBuilderTest { ...@@ -22,15 +22,13 @@ public class UrlBuilderTest {
config.setClientSecret("secret-110110110"); config.setClientSecret("secret-110110110");
config.setRedirectUri("https://xkcoding.com"); config.setRedirectUri("https://xkcoding.com");
config.setState(AuthState.create(AuthSource.WECHAT)); config.setState(AuthState.create(AuthSource.WECHAT));
// @formatter:off
String build = UrlBuilder.fromBaseUrl(AuthSource.WECHAT.authorize()) String build = UrlBuilder.fromBaseUrl(AuthSource.WECHAT.authorize())
.queryParam("appid", config.getClientId()) .queryParam("appid", config.getClientId())
.queryParam("redirect_uri", config.getRedirectUri()) .queryParam("redirect_uri", config.getRedirectUri())
.queryParam("response_type", "code") .queryParam("response_type", "code")
.queryParam("scope", "snsapi_login") .queryParam("scope", "snsapi_login")
.queryParam("state", config.getState().concat("#wechat_redirect")) .queryParam("state", config.getState().concat("#wechat_redirect"))
.build(false); .build(false);
// @formatter:on
AuthWeChatRequest request = new AuthWeChatRequest(config); AuthWeChatRequest request = new AuthWeChatRequest(config);
String authorize = request.authorize(); String authorize = request.authorize();
Assert.assertEquals(build, authorize); Assert.assertEquals(build, authorize);
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册