提交 3a04098e 编写于 作者: 智布道's avatar 智布道 👁

优化代码

上级 81691a34
...@@ -229,6 +229,11 @@ public enum AuthSource { ...@@ -229,6 +229,11 @@ public enum AuthSource {
public String userInfo() { public String userInfo() {
return "https://graph.qq.com/user/get_user_info"; return "https://graph.qq.com/user/get_user_info";
} }
@Override
public String refresh() {
return "https://graph.qq.com/oauth2.0/token";
}
}, },
/** /**
* 微信 * 微信
......
...@@ -30,6 +30,10 @@ public class AuthException extends RuntimeException { ...@@ -30,6 +30,10 @@ public class AuthException extends RuntimeException {
super(message, cause); super(message, cause);
} }
public AuthException(Throwable cause) {
super(cause);
}
public int getErrorCode() { public int getErrorCode() {
return errorCode; return errorCode;
} }
......
...@@ -9,11 +9,11 @@ import com.alipay.api.response.AlipaySystemOauthTokenResponse; ...@@ -9,11 +9,11 @@ import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse; import com.alipay.api.response.AlipayUserInfoShareResponse;
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.enums.AuthUserGender;
import me.zhyd.oauth.exception.AuthException; import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthCallback; 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.enums.AuthUserGender;
import me.zhyd.oauth.utils.StringUtils; import me.zhyd.oauth.utils.StringUtils;
import me.zhyd.oauth.utils.UrlBuilder; import me.zhyd.oauth.utils.UrlBuilder;
...@@ -43,7 +43,7 @@ public class AuthAlipayRequest extends AuthDefaultRequest { ...@@ -43,7 +43,7 @@ public class AuthAlipayRequest extends AuthDefaultRequest {
try { try {
response = this.alipayClient.execute(request); response = this.alipayClient.execute(request);
} catch (Exception e) { } catch (Exception e) {
throw new AuthException("Unable to get token from alipay using code [" + authCallback.getAuth_code() + "]", e); throw new AuthException(e);
} }
if (!response.isSuccess()) { if (!response.isSuccess()) {
throw new AuthException(response.getSubMsg()); throw new AuthException(response.getSubMsg());
......
...@@ -26,14 +26,7 @@ public class AuthBaiduRequest extends AuthDefaultRequest { ...@@ -26,14 +26,7 @@ public class AuthBaiduRequest extends AuthDefaultRequest {
@Override @Override
protected AuthToken getAccessToken(AuthCallback authCallback) { protected AuthToken getAccessToken(AuthCallback authCallback) {
HttpResponse response = doPostAuthorizationCode(authCallback.getCode()); HttpResponse response = doPostAuthorizationCode(authCallback.getCode());
JSONObject accessTokenObject = JSONObject.parseObject(response.body()); return getAuthToken(response);
this.checkResponse(accessTokenObject);
return AuthToken.builder()
.accessToken(accessTokenObject.getString("access_token"))
.refreshToken(accessTokenObject.getString("refresh_token"))
.scope(accessTokenObject.getString("scope"))
.expireIn(accessTokenObject.getIntValue("expires_in"))
.build();
} }
@Override @Override
...@@ -58,12 +51,7 @@ public class AuthBaiduRequest extends AuthDefaultRequest { ...@@ -58,12 +51,7 @@ public class AuthBaiduRequest extends AuthDefaultRequest {
public AuthResponse revoke(AuthToken authToken) { public AuthResponse revoke(AuthToken authToken) {
HttpResponse response = doGetRevoke(authToken); HttpResponse response = doGetRevoke(authToken);
JSONObject object = JSONObject.parseObject(response.body()); JSONObject object = JSONObject.parseObject(response.body());
if (object.containsKey("error_code")) { this.checkResponse(object);
return AuthResponse.builder()
.code(AuthResponseStatus.FAILURE.getCode())
.msg(object.getString("error_msg"))
.build();
}
// 返回1表示取消授权成功,否则失败 // 返回1表示取消授权成功,否则失败
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();
...@@ -78,16 +66,9 @@ public class AuthBaiduRequest extends AuthDefaultRequest { ...@@ -78,16 +66,9 @@ public class AuthBaiduRequest extends AuthDefaultRequest {
.queryParam("client_secret", this.config.getClientSecret()) .queryParam("client_secret", this.config.getClientSecret())
.build(); .build();
HttpResponse response = HttpRequest.get(refreshUrl).execute(); HttpResponse response = HttpRequest.get(refreshUrl).execute();
JSONObject object = JSONObject.parseObject(response.body());
this.checkResponse(object);
return AuthResponse.builder() return AuthResponse.builder()
.code(AuthResponseStatus.SUCCESS.getCode()) .code(AuthResponseStatus.SUCCESS.getCode())
.data(AuthToken.builder() .data(this.getAuthToken(response))
.accessToken(object.getString("access_token"))
.refreshToken(object.getString("refresh_token"))
.scope(object.getString("scope"))
.expireIn(object.getIntValue("expires_in"))
.build())
.build(); .build();
} }
...@@ -107,9 +88,26 @@ public class AuthBaiduRequest extends AuthDefaultRequest { ...@@ -107,9 +88,26 @@ public class AuthBaiduRequest extends AuthDefaultRequest {
.build(); .build();
} }
/**
* 检查响应内容是否正确
*
* @param object 请求响应内容
*/
private void checkResponse(JSONObject object) { private void checkResponse(JSONObject object) {
if (object.containsKey("error")) { if (object.containsKey("error") || object.containsKey("error_code")) {
throw new AuthException(object.getString("error_description")); String msg = object.containsKey("error_description") ? object.getString("error_description") : object.getString("error_msg");
throw new AuthException(msg);
} }
} }
private AuthToken getAuthToken(HttpResponse response) {
JSONObject accessTokenObject = JSONObject.parseObject(response.body());
this.checkResponse(accessTokenObject);
return AuthToken.builder()
.accessToken(accessTokenObject.getString("access_token"))
.refreshToken(accessTokenObject.getString("refresh_token"))
.scope(accessTokenObject.getString("scope"))
.expireIn(accessTokenObject.getIntValue("expires_in"))
.build();
}
} }
...@@ -28,9 +28,7 @@ public class AuthCodingRequest extends AuthDefaultRequest { ...@@ -28,9 +28,7 @@ public class AuthCodingRequest extends AuthDefaultRequest {
protected AuthToken getAccessToken(AuthCallback authCallback) { protected AuthToken getAccessToken(AuthCallback authCallback) {
HttpResponse response = doGetAuthorizationCode(authCallback.getCode()); HttpResponse response = doGetAuthorizationCode(authCallback.getCode());
JSONObject accessTokenObject = JSONObject.parseObject(response.body()); JSONObject accessTokenObject = JSONObject.parseObject(response.body());
if (accessTokenObject.getIntValue("code") != 0) { this.checkResponse(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"))
...@@ -42,9 +40,7 @@ public class AuthCodingRequest extends AuthDefaultRequest { ...@@ -42,9 +40,7 @@ public class AuthCodingRequest extends AuthDefaultRequest {
protected AuthUser getUserInfo(AuthToken authToken) { protected AuthUser getUserInfo(AuthToken authToken) {
HttpResponse response = doGetUserInfo(authToken); HttpResponse response = doGetUserInfo(authToken);
JSONObject object = JSONObject.parseObject(response.body()); JSONObject object = JSONObject.parseObject(response.body());
if (object.getIntValue("code") != 0) { this.checkResponse(object);
throw new AuthException(object.getString("msg"));
}
object = object.getJSONObject("data"); object = object.getJSONObject("data");
return AuthUser.builder() return AuthUser.builder()
...@@ -63,6 +59,17 @@ public class AuthCodingRequest extends AuthDefaultRequest { ...@@ -63,6 +59,17 @@ public class AuthCodingRequest extends AuthDefaultRequest {
.build(); .build();
} }
/**
* 检查响应内容是否正确
*
* @param object 请求响应内容
*/
private void checkResponse(JSONObject object) {
if (object.getIntValue("code") != 0) {
throw new AuthException(object.getString("msg"));
}
}
/** /**
* 返回认证url,可自行跳转页面 * 返回认证url,可自行跳转页面
* *
......
...@@ -4,11 +4,11 @@ import cn.hutool.http.HttpResponse; ...@@ -4,11 +4,11 @@ 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.enums.AuthUserGender;
import me.zhyd.oauth.exception.AuthException; import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthCallback; 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.enums.AuthUserGender;
/** /**
* CSDN登录 * CSDN登录
...@@ -28,9 +28,7 @@ public class AuthCsdnRequest extends AuthDefaultRequest { ...@@ -28,9 +28,7 @@ public class AuthCsdnRequest extends AuthDefaultRequest {
protected AuthToken getAccessToken(AuthCallback authCallback) { protected AuthToken getAccessToken(AuthCallback authCallback) {
HttpResponse response = doPostAuthorizationCode(authCallback.getCode()); HttpResponse response = doPostAuthorizationCode(authCallback.getCode());
JSONObject accessTokenObject = JSONObject.parseObject(response.body()); JSONObject accessTokenObject = JSONObject.parseObject(response.body());
if (accessTokenObject.containsKey("error_code")) { this.checkResponse(accessTokenObject);
throw new AuthException("Unable to get token from csdn using code [" + authCallback.getCode() + "]: " + accessTokenObject);
}
return AuthToken.builder().accessToken(accessTokenObject.getString("access_token")).build(); return AuthToken.builder().accessToken(accessTokenObject.getString("access_token")).build();
} }
...@@ -38,9 +36,7 @@ public class AuthCsdnRequest extends AuthDefaultRequest { ...@@ -38,9 +36,7 @@ public class AuthCsdnRequest extends AuthDefaultRequest {
protected AuthUser getUserInfo(AuthToken authToken) { protected AuthUser getUserInfo(AuthToken authToken) {
HttpResponse response = doGetUserInfo(authToken); HttpResponse response = doGetUserInfo(authToken);
JSONObject object = JSONObject.parseObject(response.body()); JSONObject object = JSONObject.parseObject(response.body());
if (object.containsKey("error_code")) { this.checkResponse(object);
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"))
...@@ -51,4 +47,15 @@ public class AuthCsdnRequest extends AuthDefaultRequest { ...@@ -51,4 +47,15 @@ public class AuthCsdnRequest extends AuthDefaultRequest {
.source(AuthSource.CSDN) .source(AuthSource.CSDN)
.build(); .build();
} }
/**
* 检查响应内容是否正确
*
* @param object 请求响应内容
*/
private void checkResponse(JSONObject object) {
if (object.containsKey("error_code")) {
throw new AuthException(object.getString("error"));
}
}
} }
...@@ -3,6 +3,7 @@ package me.zhyd.oauth.request; ...@@ -3,6 +3,7 @@ package me.zhyd.oauth.request;
import cn.hutool.http.HttpRequest; import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse; import cn.hutool.http.HttpResponse;
import lombok.Data; import lombok.Data;
import lombok.extern.slf4j.Slf4j;
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;
...@@ -20,6 +21,7 @@ import me.zhyd.oauth.utils.UrlBuilder; ...@@ -20,6 +21,7 @@ import me.zhyd.oauth.utils.UrlBuilder;
* @since 1.8 * @since 1.8
*/ */
@Data @Data
@Slf4j
public abstract class AuthDefaultRequest implements AuthRequest { public abstract class AuthDefaultRequest implements AuthRequest {
protected AuthConfig config; protected AuthConfig config;
protected AuthSource source; protected AuthSource source;
...@@ -48,6 +50,7 @@ public abstract class AuthDefaultRequest implements AuthRequest { ...@@ -48,6 +50,7 @@ public abstract class AuthDefaultRequest implements AuthRequest {
AuthUser user = this.getUserInfo(authToken); AuthUser user = this.getUserInfo(authToken);
return AuthResponse.builder().code(AuthResponseStatus.SUCCESS.getCode()).data(user).build(); return AuthResponse.builder().code(AuthResponseStatus.SUCCESS.getCode()).data(user).build();
} catch (Exception e) { } catch (Exception e) {
log.error("Failed to login with oauth authorization.", e);
return this.responseError(e); return this.responseError(e);
} }
} }
......
...@@ -32,10 +32,8 @@ public class AuthDouyinRequest extends AuthDefaultRequest { ...@@ -32,10 +32,8 @@ public class AuthDouyinRequest extends AuthDefaultRequest {
@Override @Override
protected AuthUser getUserInfo(AuthToken authToken) { protected AuthUser getUserInfo(AuthToken authToken) {
HttpResponse response = doGetUserInfo(authToken); HttpResponse response = doGetUserInfo(authToken);
JSONObject object = JSONObject.parseObject(response.body()); JSONObject userInfoObject = JSONObject.parseObject(response.body());
this.checkResponse(userInfoObject);
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"))
...@@ -52,7 +50,7 @@ public class AuthDouyinRequest extends AuthDefaultRequest { ...@@ -52,7 +50,7 @@ public class AuthDouyinRequest extends AuthDefaultRequest {
public AuthResponse refresh(AuthToken oldToken) { public AuthResponse refresh(AuthToken oldToken) {
return AuthResponse.builder() return AuthResponse.builder()
.code(AuthResponseStatus.SUCCESS.getCode()) .code(AuthResponseStatus.SUCCESS.getCode())
.data(refreshTokenUrl(oldToken.getRefreshToken())) .data(getToken(refreshTokenUrl(oldToken.getRefreshToken())))
.build(); .build();
} }
...@@ -60,16 +58,14 @@ public class AuthDouyinRequest extends AuthDefaultRequest { ...@@ -60,16 +58,14 @@ public class AuthDouyinRequest extends AuthDefaultRequest {
* 检查响应内容是否正确 * 检查响应内容是否正确
* *
* @param object 请求响应内容 * @param object 请求响应内容
* @return 实际请求数据的json对象
*/ */
private JSONObject checkResponse(JSONObject object) { private void checkResponse(JSONObject object) {
String message = object.getString("message"); String message = object.getString("message");
JSONObject data = object.getJSONObject("data"); JSONObject data = object.getJSONObject("data");
int errorCode = data.getIntValue("error_code"); int errorCode = data.getIntValue("error_code");
if ("error".equals(message) || errorCode != 0) { if ("error".equals(message) || errorCode != 0) {
throw new AuthException(errorCode, data.getString("description")); throw new AuthException(errorCode, data.getString("description"));
} }
return data;
} }
/** /**
...@@ -82,14 +78,13 @@ public class AuthDouyinRequest extends AuthDefaultRequest { ...@@ -82,14 +78,13 @@ public class AuthDouyinRequest extends AuthDefaultRequest {
HttpResponse response = HttpRequest.post(accessTokenUrl).execute(); HttpResponse response = HttpRequest.post(accessTokenUrl).execute();
String accessTokenStr = response.body(); String accessTokenStr = response.body();
JSONObject object = JSONObject.parseObject(accessTokenStr); JSONObject object = JSONObject.parseObject(accessTokenStr);
this.checkResponse(object);
JSONObject accessTokenObject = this.checkResponse(object);
return AuthToken.builder() return AuthToken.builder()
.accessToken(accessTokenObject.getString("access_token")) .accessToken(object.getString("access_token"))
.openId(accessTokenObject.getString("open_id")) .openId(object.getString("open_id"))
.expireIn(accessTokenObject.getIntValue("expires_in")) .expireIn(object.getIntValue("expires_in"))
.refreshToken(accessTokenObject.getString("refresh_token")) .refreshToken(object.getString("refresh_token"))
.scope(accessTokenObject.getString("scope")) .scope(object.getString("scope"))
.build(); .build();
} }
...@@ -112,7 +107,7 @@ public class AuthDouyinRequest extends AuthDefaultRequest { ...@@ -112,7 +107,7 @@ public class AuthDouyinRequest extends AuthDefaultRequest {
/** /**
* 返回获取accessToken的url * 返回获取accessToken的url
* *
* @param code * @param code oauth的授权码
* @return 返回获取accessToken的url * @return 返回获取accessToken的url
*/ */
@Override @Override
...@@ -128,7 +123,7 @@ public class AuthDouyinRequest extends AuthDefaultRequest { ...@@ -128,7 +123,7 @@ public class AuthDouyinRequest extends AuthDefaultRequest {
/** /**
* 返回获取userInfo的url * 返回获取userInfo的url
* *
* @param authToken * @param authToken oauth返回的token
* @return 返回获取userInfo的url * @return 返回获取userInfo的url
*/ */
@Override @Override
...@@ -142,7 +137,7 @@ public class AuthDouyinRequest extends AuthDefaultRequest { ...@@ -142,7 +137,7 @@ public class AuthDouyinRequest extends AuthDefaultRequest {
/** /**
* 返回获取accessToken的url * 返回获取accessToken的url
* *
* @param refreshToken * @param refreshToken oauth返回的refreshtoken
* @return 返回获取accessToken的url * @return 返回获取accessToken的url
*/ */
@Override @Override
......
...@@ -4,11 +4,11 @@ import cn.hutool.http.HttpResponse; ...@@ -4,11 +4,11 @@ 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.enums.AuthUserGender;
import me.zhyd.oauth.exception.AuthException; import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthCallback; 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.enums.AuthUserGender;
import me.zhyd.oauth.utils.UrlBuilder; import me.zhyd.oauth.utils.UrlBuilder;
/** /**
...@@ -28,11 +28,7 @@ public class AuthFacebookRequest extends AuthDefaultRequest { ...@@ -28,11 +28,7 @@ public class AuthFacebookRequest extends AuthDefaultRequest {
protected AuthToken getAccessToken(AuthCallback authCallback) { protected AuthToken getAccessToken(AuthCallback authCallback) {
HttpResponse response = doPostAuthorizationCode(authCallback.getCode()); HttpResponse response = doPostAuthorizationCode(authCallback.getCode());
JSONObject accessTokenObject = JSONObject.parseObject(response.body()); JSONObject accessTokenObject = JSONObject.parseObject(response.body());
this.checkResponse(accessTokenObject);
if (accessTokenObject.containsKey("error")) {
throw new AuthException(accessTokenObject.getJSONObject("error").getString("message"));
}
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"))
...@@ -45,22 +41,12 @@ public class AuthFacebookRequest extends AuthDefaultRequest { ...@@ -45,22 +41,12 @@ public class AuthFacebookRequest extends AuthDefaultRequest {
HttpResponse response = doGetUserInfo(authToken); HttpResponse response = doGetUserInfo(authToken);
String userInfo = response.body(); String userInfo = response.body();
JSONObject object = JSONObject.parseObject(userInfo); JSONObject object = JSONObject.parseObject(userInfo);
if (object.containsKey("error")) { this.checkResponse(object);
throw new AuthException(object.getJSONObject("error").getString("message"));
}
String picture = null;
if (object.containsKey("picture")) {
JSONObject pictureObj = object.getJSONObject("picture");
pictureObj = pictureObj.getJSONObject("data");
if (null != pictureObj) {
picture = pictureObj.getString("url");
}
}
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(getUserPicture(object))
.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")))
...@@ -69,10 +55,22 @@ public class AuthFacebookRequest extends AuthDefaultRequest { ...@@ -69,10 +55,22 @@ public class AuthFacebookRequest extends AuthDefaultRequest {
.build(); .build();
} }
private String getUserPicture(JSONObject object) {
String picture = null;
if (object.containsKey("picture")) {
JSONObject pictureObj = object.getJSONObject("picture");
pictureObj = pictureObj.getJSONObject("data");
if (null != pictureObj) {
picture = pictureObj.getString("url");
}
}
return picture;
}
/** /**
* 返回获取userInfo的url * 返回获取userInfo的url
* *
* @param authToken * @param authToken 用户token
* @return 返回获取userInfo的url * @return 返回获取userInfo的url
*/ */
@Override @Override
...@@ -82,4 +80,15 @@ public class AuthFacebookRequest extends AuthDefaultRequest { ...@@ -82,4 +80,15 @@ public class AuthFacebookRequest extends AuthDefaultRequest {
.queryParam("fields", "id,name,birthday,gender,hometown,email,devices,picture.width(400)") .queryParam("fields", "id,name,birthday,gender,hometown,email,devices,picture.width(400)")
.build(); .build();
} }
/**
* 检查响应内容是否正确
*
* @param object 请求响应内容
*/
private void checkResponse(JSONObject object) {
if (object.containsKey("error")) {
throw new AuthException(object.getJSONObject("error").getString("message"));
}
}
} }
...@@ -4,11 +4,11 @@ import cn.hutool.http.HttpResponse; ...@@ -4,11 +4,11 @@ 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.enums.AuthUserGender;
import me.zhyd.oauth.exception.AuthException; import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthCallback; 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.enums.AuthUserGender;
/** /**
* Gitee登录 * Gitee登录
...@@ -27,9 +27,7 @@ public class AuthGiteeRequest extends AuthDefaultRequest { ...@@ -27,9 +27,7 @@ public class AuthGiteeRequest extends AuthDefaultRequest {
protected AuthToken getAccessToken(AuthCallback authCallback) { protected AuthToken getAccessToken(AuthCallback authCallback) {
HttpResponse response = doPostAuthorizationCode(authCallback.getCode()); HttpResponse response = doPostAuthorizationCode(authCallback.getCode());
JSONObject accessTokenObject = JSONObject.parseObject(response.body()); JSONObject accessTokenObject = JSONObject.parseObject(response.body());
if (accessTokenObject.containsKey("error")) { this.checkResponse(accessTokenObject);
throw new AuthException("Unable to get token from gitee 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"))
...@@ -44,6 +42,7 @@ public class AuthGiteeRequest extends AuthDefaultRequest { ...@@ -44,6 +42,7 @@ public class AuthGiteeRequest extends AuthDefaultRequest {
HttpResponse response = doGetUserInfo(authToken); HttpResponse response = doGetUserInfo(authToken);
String userInfo = response.body(); String userInfo = response.body();
JSONObject object = JSONObject.parseObject(userInfo); JSONObject object = JSONObject.parseObject(userInfo);
this.checkResponse(object);
return AuthUser.builder() return AuthUser.builder()
.uuid(object.getString("id")) .uuid(object.getString("id"))
.username(object.getString("login")) .username(object.getString("login"))
...@@ -59,4 +58,15 @@ public class AuthGiteeRequest extends AuthDefaultRequest { ...@@ -59,4 +58,15 @@ public class AuthGiteeRequest extends AuthDefaultRequest {
.source(AuthSource.GITEE) .source(AuthSource.GITEE)
.build(); .build();
} }
/**
* 检查响应内容是否正确
*
* @param object 请求响应内容
*/
private void checkResponse(JSONObject object) {
if (object.containsKey("error")) {
throw new AuthException(object.getString("error_description"));
}
}
} }
...@@ -4,14 +4,11 @@ import cn.hutool.http.HttpResponse; ...@@ -4,14 +4,11 @@ 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.enums.AuthUserGender;
import me.zhyd.oauth.exception.AuthException; import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthCallback; 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.enums.AuthUserGender;
import me.zhyd.oauth.utils.GlobalAuthUtil;
import java.util.Map;
/** /**
* Github登录 * Github登录
...@@ -29,22 +26,20 @@ public class AuthGithubRequest extends AuthDefaultRequest { ...@@ -29,22 +26,20 @@ public class AuthGithubRequest extends AuthDefaultRequest {
@Override @Override
protected AuthToken getAccessToken(AuthCallback authCallback) { protected AuthToken getAccessToken(AuthCallback authCallback) {
HttpResponse response = doPostAuthorizationCode(authCallback.getCode()); HttpResponse response = doPostAuthorizationCode(authCallback.getCode());
Map<String, String> res = GlobalAuthUtil.parseStringToMap(response.body()); JSONObject accessTokenObject = JSONObject.parseObject(response.body());
if (res.containsKey("error")) { this.checkResponse(accessTokenObject);
throw new AuthException(res.get("error") + ":" + res.get("error_description"));
}
return AuthToken.builder() return AuthToken.builder()
.accessToken(res.get("access_token")) .accessToken(accessTokenObject.getString("access_token"))
.scope(res.get("scope")) .scope(accessTokenObject.getString("scope"))
.tokenType(res.get("token_type")) .tokenType(accessTokenObject.getString("token_type"))
.build(); .build();
} }
@Override @Override
protected AuthUser getUserInfo(AuthToken authToken) { protected AuthUser getUserInfo(AuthToken authToken) {
HttpResponse response = doGetUserInfo(authToken); HttpResponse response = doGetUserInfo(authToken);
String userInfo = response.body(); JSONObject object = JSONObject.parseObject(response.body());
JSONObject object = JSONObject.parseObject(userInfo); this.checkResponse(object);
return AuthUser.builder() return AuthUser.builder()
.uuid(object.getString("id")) .uuid(object.getString("id"))
.username(object.getString("login")) .username(object.getString("login"))
...@@ -60,4 +55,15 @@ public class AuthGithubRequest extends AuthDefaultRequest { ...@@ -60,4 +55,15 @@ public class AuthGithubRequest extends AuthDefaultRequest {
.source(AuthSource.GITHUB) .source(AuthSource.GITHUB)
.build(); .build();
} }
/**
* 检查响应内容是否正确
*
* @param object 请求响应内容
*/
private void checkResponse(JSONObject object) {
if (object.containsKey("error")) {
throw new AuthException(object.getString("error_description"));
}
}
} }
...@@ -4,11 +4,11 @@ import cn.hutool.http.HttpResponse; ...@@ -4,11 +4,11 @@ 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.enums.AuthUserGender;
import me.zhyd.oauth.exception.AuthException; import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthCallback; 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.enums.AuthUserGender;
import me.zhyd.oauth.utils.UrlBuilder; import me.zhyd.oauth.utils.UrlBuilder;
/** /**
...@@ -28,12 +28,7 @@ public class AuthGoogleRequest extends AuthDefaultRequest { ...@@ -28,12 +28,7 @@ public class AuthGoogleRequest extends AuthDefaultRequest {
protected AuthToken getAccessToken(AuthCallback authCallback) { protected AuthToken getAccessToken(AuthCallback authCallback) {
HttpResponse response = doPostAuthorizationCode(authCallback.getCode()); HttpResponse response = doPostAuthorizationCode(authCallback.getCode());
JSONObject accessTokenObject = JSONObject.parseObject(response.body()); JSONObject accessTokenObject = JSONObject.parseObject(response.body());
this.checkResponse(accessTokenObject);
if (accessTokenObject.containsKey("error") || accessTokenObject.containsKey("error_description")) {
throw new AuthException("get google access_token has error:[" + accessTokenObject.getString("error") + "], error_description:[" + accessTokenObject
.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"))
...@@ -48,6 +43,7 @@ public class AuthGoogleRequest extends AuthDefaultRequest { ...@@ -48,6 +43,7 @@ public class AuthGoogleRequest extends AuthDefaultRequest {
HttpResponse response = doGetUserInfo(authToken); HttpResponse response = doGetUserInfo(authToken);
String userInfo = response.body(); String userInfo = response.body();
JSONObject object = JSONObject.parseObject(userInfo); JSONObject object = JSONObject.parseObject(userInfo);
this.checkResponse(object);
return AuthUser.builder() return AuthUser.builder()
.uuid(object.getString("sub")) .uuid(object.getString("sub"))
.username(object.getString("name")) .username(object.getString("name"))
...@@ -87,4 +83,15 @@ public class AuthGoogleRequest extends AuthDefaultRequest { ...@@ -87,4 +83,15 @@ public class AuthGoogleRequest extends AuthDefaultRequest {
protected String userInfoUrl(AuthToken authToken) { protected String userInfoUrl(AuthToken authToken) {
return UrlBuilder.fromBaseUrl(source.userInfo()).queryParam("id_token", authToken.getAccessToken()).build(); return UrlBuilder.fromBaseUrl(source.userInfo()).queryParam("id_token", authToken.getAccessToken()).build();
} }
/**
* 检查响应内容是否正确
*
* @param object 请求响应内容
*/
private void checkResponse(JSONObject object) {
if (object.containsKey("error") || object.containsKey("error_description")) {
throw new AuthException(object.getString("error_description"));
}
}
} }
...@@ -43,7 +43,32 @@ public class AuthLinkedinRequest extends AuthDefaultRequest { ...@@ -43,7 +43,32 @@ public class AuthLinkedinRequest extends AuthDefaultRequest {
this.checkResponse(userInfoObject); this.checkResponse(userInfoObject);
// 组装用户名 String userName = getUserName(userInfoObject);
// 获取用户头像
String avatar = this.getAvatar(userInfoObject);
// 获取用户邮箱地址
String email = this.getUserEmail(accessToken);
return AuthUser.builder()
.uuid(userInfoObject.getString("id"))
.username(userName)
.nickname(userName)
.avatar(avatar)
.email(email)
.token(authToken)
.gender(AuthUserGender.UNKNOWN)
.source(AuthSource.LINKEDIN)
.build();
}
/**
* 获取用户的真实名
*
* @param userInfoObject 用户json对象
* @return 用户名
*/
private String getUserName(JSONObject userInfoObject) {
String firstName, lastName; String firstName, lastName;
// 获取firstName // 获取firstName
if (userInfoObject.containsKey("localizedFirstName")) { if (userInfoObject.containsKey("localizedFirstName")) {
...@@ -57,9 +82,16 @@ public class AuthLinkedinRequest extends AuthDefaultRequest { ...@@ -57,9 +82,16 @@ public class AuthLinkedinRequest extends AuthDefaultRequest {
} else { } else {
lastName = getUserName(userInfoObject, "lastName"); lastName = getUserName(userInfoObject, "lastName");
} }
String userName = firstName + " " + lastName; return firstName + " " + lastName;
}
// 获取用户头像 /**
* 获取用户的头像
*
* @param userInfoObject 用户json对象
* @return 用户的头像地址
*/
private String getAvatar(JSONObject userInfoObject) {
String avatar = null; String avatar = null;
JSONObject profilePictureObject = userInfoObject.getJSONObject("profilePicture"); JSONObject profilePictureObject = userInfoObject.getJSONObject("profilePicture");
if (profilePictureObject.containsKey("displayImage~")) { if (profilePictureObject.containsKey("displayImage~")) {
...@@ -70,21 +102,15 @@ public class AuthLinkedinRequest extends AuthDefaultRequest { ...@@ -70,21 +102,15 @@ public class AuthLinkedinRequest extends AuthDefaultRequest {
avatar = largestImageObj.getJSONArray("identifiers").getJSONObject(0).getString("identifier"); avatar = largestImageObj.getJSONArray("identifiers").getJSONObject(0).getString("identifier");
} }
} }
return avatar;
// 获取用户邮箱地址
String email = this.getUserEmail(accessToken);
return AuthUser.builder()
.uuid(userInfoObject.getString("id"))
.username(userName)
.nickname(userName)
.avatar(avatar)
.email(email)
.token(authToken)
.gender(AuthUserGender.UNKNOWN)
.source(AuthSource.LINKEDIN)
.build();
} }
/**
* 获取用户的email
*
* @param accessToken 用户授权后返回的token
* @return 用户的邮箱地址
*/
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~))")
...@@ -92,8 +118,8 @@ public class AuthLinkedinRequest extends AuthDefaultRequest { ...@@ -92,8 +118,8 @@ public class AuthLinkedinRequest extends AuthDefaultRequest {
.header("Connection", "Keep-Alive") .header("Connection", "Keep-Alive")
.header("Authorization", "Bearer " + accessToken) .header("Authorization", "Bearer " + accessToken)
.execute(); .execute();
System.out.println(emailResponse.body());
JSONObject emailObj = JSONObject.parseObject(emailResponse.body()); JSONObject emailObj = JSONObject.parseObject(emailResponse.body());
this.checkResponse(emailObj);
if (emailObj.containsKey("elements")) { if (emailObj.containsKey("elements")) {
email = emailObj.getJSONArray("elements") email = emailObj.getJSONArray("elements")
.getJSONObject(0) .getJSONObject(0)
...@@ -125,9 +151,14 @@ public class AuthLinkedinRequest extends AuthDefaultRequest { ...@@ -125,9 +151,14 @@ public class AuthLinkedinRequest extends AuthDefaultRequest {
.build(); .build();
} }
private void checkResponse(JSONObject userInfoObject) { /**
if (userInfoObject.containsKey("error")) { * 检查响应内容是否正确
throw new AuthException(userInfoObject.getString("error_description")); *
* @param object 请求响应内容
*/
private void checkResponse(JSONObject object) {
if (object.containsKey("error")) {
throw new AuthException(object.getString("error_description"));
} }
} }
......
...@@ -55,9 +55,14 @@ public class AuthMicrosoftRequest extends AuthDefaultRequest { ...@@ -55,9 +55,14 @@ public class AuthMicrosoftRequest extends AuthDefaultRequest {
.build(); .build();
} }
private void checkResponse(JSONObject response) { /**
if (response.containsKey("error")) { * 检查响应内容是否正确
throw new AuthException(response.getString("error_description")); *
* @param object 请求响应内容
*/
private void checkResponse(JSONObject object) {
if (object.containsKey("error")) {
throw new AuthException(object.getString("error_description"));
} }
} }
...@@ -69,6 +74,7 @@ public class AuthMicrosoftRequest extends AuthDefaultRequest { ...@@ -69,6 +74,7 @@ public class AuthMicrosoftRequest extends AuthDefaultRequest {
HttpResponse response = HttpRequest.get(userInfoUrl(authToken)).header("Authorization", jwt).execute(); HttpResponse response = HttpRequest.get(userInfoUrl(authToken)).header("Authorization", jwt).execute();
String userInfo = response.body(); String userInfo = response.body();
JSONObject object = JSONObject.parseObject(userInfo); JSONObject object = JSONObject.parseObject(userInfo);
this.checkResponse(object);
return AuthUser.builder() return AuthUser.builder()
.uuid(object.getString("id")) .uuid(object.getString("id"))
.username(object.getString("userPrincipalName")) .username(object.getString("userPrincipalName"))
......
...@@ -4,11 +4,11 @@ import cn.hutool.http.HttpResponse; ...@@ -4,11 +4,11 @@ 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.enums.AuthUserGender;
import me.zhyd.oauth.exception.AuthException; import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthCallback; 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.enums.AuthUserGender;
import me.zhyd.oauth.utils.UrlBuilder; import me.zhyd.oauth.utils.UrlBuilder;
/** /**
...@@ -28,9 +28,7 @@ public class AuthOschinaRequest extends AuthDefaultRequest { ...@@ -28,9 +28,7 @@ public class AuthOschinaRequest extends AuthDefaultRequest {
protected AuthToken getAccessToken(AuthCallback authCallback) { protected AuthToken getAccessToken(AuthCallback authCallback) {
HttpResponse response = doPostAuthorizationCode(authCallback.getCode()); HttpResponse response = doPostAuthorizationCode(authCallback.getCode());
JSONObject accessTokenObject = JSONObject.parseObject(response.body()); JSONObject accessTokenObject = JSONObject.parseObject(response.body());
if (accessTokenObject.containsKey("error")) { this.checkResponse(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"))
...@@ -43,9 +41,7 @@ public class AuthOschinaRequest extends AuthDefaultRequest { ...@@ -43,9 +41,7 @@ public class AuthOschinaRequest extends AuthDefaultRequest {
protected AuthUser getUserInfo(AuthToken authToken) { protected AuthUser getUserInfo(AuthToken authToken) {
HttpResponse response = doGetUserInfo(authToken); HttpResponse response = doGetUserInfo(authToken);
JSONObject object = JSONObject.parseObject(response.body()); JSONObject object = JSONObject.parseObject(response.body());
if (object.containsKey("error")) { this.checkResponse(object);
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"))
...@@ -91,4 +87,15 @@ public class AuthOschinaRequest extends AuthDefaultRequest { ...@@ -91,4 +87,15 @@ public class AuthOschinaRequest extends AuthDefaultRequest {
.queryParam("dataType", "json") .queryParam("dataType", "json")
.build(); .build();
} }
/**
* 检查响应内容是否正确
*
* @param object 请求响应内容
*/
private void checkResponse(JSONObject object) {
if (object.containsKey("error")) {
throw new AuthException(object.getString("error_description"));
}
}
} }
...@@ -4,11 +4,11 @@ import cn.hutool.http.HttpRequest; ...@@ -4,11 +4,11 @@ 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.enums.AuthUserGender;
import me.zhyd.oauth.exception.AuthException; import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthCallback; 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.enums.AuthUserGender;
import me.zhyd.oauth.utils.UrlBuilder; import me.zhyd.oauth.utils.UrlBuilder;
import java.util.Objects; import java.util.Objects;
...@@ -24,6 +24,8 @@ import static me.zhyd.oauth.config.AuthSource.PINTEREST; ...@@ -24,6 +24,8 @@ import static me.zhyd.oauth.config.AuthSource.PINTEREST;
*/ */
public class AuthPinterestRequest extends AuthDefaultRequest { public class AuthPinterestRequest extends AuthDefaultRequest {
private static final String FAILURE = "failure";
public AuthPinterestRequest(AuthConfig config) { public AuthPinterestRequest(AuthConfig config) {
super(config, PINTEREST); super(config, PINTEREST);
} }
...@@ -32,10 +34,7 @@ public class AuthPinterestRequest extends AuthDefaultRequest { ...@@ -32,10 +34,7 @@ public class AuthPinterestRequest extends AuthDefaultRequest {
protected AuthToken getAccessToken(AuthCallback authCallback) { protected AuthToken getAccessToken(AuthCallback authCallback) {
HttpResponse response = doPostAuthorizationCode(authCallback.getCode()); HttpResponse response = doPostAuthorizationCode(authCallback.getCode());
JSONObject accessTokenObject = JSONObject.parseObject(response.body()); JSONObject accessTokenObject = JSONObject.parseObject(response.body());
if (!response.isOk()) { this.checkResponse(accessTokenObject);
throw new AuthException("Unable to get token from Pinterest using code [" + authCallback.getCode() + "]: " + accessTokenObject);
}
return AuthToken.builder() return AuthToken.builder()
.accessToken(accessTokenObject.getString("access_token")) .accessToken(accessTokenObject.getString("access_token"))
.tokenType(accessTokenObject.getString("token_type")) .tokenType(accessTokenObject.getString("token_type"))
...@@ -48,8 +47,9 @@ public class AuthPinterestRequest extends AuthDefaultRequest { ...@@ -48,8 +47,9 @@ public class AuthPinterestRequest extends AuthDefaultRequest {
.queryParam("fields", "id,username,first_name,last_name,bio,image") .queryParam("fields", "id,username,first_name,last_name,bio,image")
.build(); .build();
HttpResponse response = HttpRequest.post(userinfoUrl).execute(); HttpResponse response = HttpRequest.post(userinfoUrl).execute();
JSONObject userObj = JSONObject.parseObject(response.body()).getJSONObject("data"); JSONObject object = JSONObject.parseObject(response.body());
this.checkResponse(object);
JSONObject userObj = object.getJSONObject("data");
return AuthUser.builder() return AuthUser.builder()
.uuid(userObj.getString("id")) .uuid(userObj.getString("id"))
.avatar(getAvatarUrl(userObj)) .avatar(getAvatarUrl(userObj))
...@@ -82,4 +82,15 @@ public class AuthPinterestRequest extends AuthDefaultRequest { ...@@ -82,4 +82,15 @@ public class AuthPinterestRequest extends AuthDefaultRequest {
.build(); .build();
} }
/**
* 检查响应内容是否正确
*
* @param object 请求响应内容
*/
private void checkResponse(JSONObject object) {
if (!object.containsKey("status") && FAILURE.equals(object.getString("status"))) {
throw new AuthException(object.getString("message"));
}
}
} }
...@@ -6,11 +6,9 @@ import cn.hutool.http.HttpResponse; ...@@ -6,11 +6,9 @@ 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.model.AuthCallback;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.enums.AuthUserGender; import me.zhyd.oauth.enums.AuthUserGender;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.*;
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 me.zhyd.oauth.utils.UrlBuilder;
...@@ -33,14 +31,15 @@ public class AuthQqRequest extends AuthDefaultRequest { ...@@ -33,14 +31,15 @@ public class AuthQqRequest extends AuthDefaultRequest {
@Override @Override
protected AuthToken getAccessToken(AuthCallback authCallback) { protected AuthToken getAccessToken(AuthCallback authCallback) {
HttpResponse response = doGetAuthorizationCode(authCallback.getCode()); HttpResponse response = doGetAuthorizationCode(authCallback.getCode());
Map<String, String> accessTokenObject = GlobalAuthUtil.parseStringToMap(response.body()); return getAuthToken(response);
if (!accessTokenObject.containsKey("access_token")) { }
throw new AuthException("Unable to get token from qq using code [" + authCallback.getCode() + "]: " + accessTokenObject);
} @Override
return AuthToken.builder() public AuthResponse refresh(AuthToken authToken) {
.accessToken(accessTokenObject.get("access_token")) HttpResponse response = HttpRequest.get(refreshTokenUrl(authToken.getRefreshToken())).execute();
.expireIn(Integer.valueOf(accessTokenObject.get("expires_in"))) return AuthResponse.builder()
.refreshToken(accessTokenObject.get("refresh_token")) .code(AuthResponseStatus.SUCCESS.getCode())
.data(getAuthToken(response))
.build(); .build();
} }
...@@ -97,7 +96,7 @@ public class AuthQqRequest extends AuthDefaultRequest { ...@@ -97,7 +96,7 @@ public class AuthQqRequest extends AuthDefaultRequest {
/** /**
* 返回获取userInfo的url * 返回获取userInfo的url
* *
* @param authToken * @param authToken 用户授权token
* @return 返回获取userInfo的url * @return 返回获取userInfo的url
*/ */
@Override @Override
...@@ -108,4 +107,16 @@ public class AuthQqRequest extends AuthDefaultRequest { ...@@ -108,4 +107,16 @@ public class AuthQqRequest extends AuthDefaultRequest {
.queryParam("openid", authToken.getOpenId()) .queryParam("openid", authToken.getOpenId())
.build(); .build();
} }
private AuthToken getAuthToken(HttpResponse response) {
Map<String, String> accessTokenObject = GlobalAuthUtil.parseStringToMap(response.body());
if (!accessTokenObject.containsKey("access_token") || accessTokenObject.containsKey("code")) {
throw new AuthException(accessTokenObject.get("msg"));
}
return AuthToken.builder()
.accessToken(accessTokenObject.get("access_token"))
.expireIn(Integer.valueOf(accessTokenObject.get("expires_in")))
.refreshToken(accessTokenObject.get("refresh_token"))
.build();
}
} }
...@@ -60,7 +60,7 @@ public class AuthRenrenRequest extends AuthDefaultRequest { ...@@ -60,7 +60,7 @@ public class AuthRenrenRequest extends AuthDefaultRequest {
private AuthToken getToken(String url) { private AuthToken getToken(String url) {
HttpResponse response = HttpRequest.post(url).execute(); HttpResponse response = HttpRequest.post(url).execute();
JSONObject jsonObject = JSONObject.parseObject(response.body()); JSONObject jsonObject = JSONObject.parseObject(response.body());
if (!response.isOk()) { if (jsonObject.containsKey("error")) {
throw new AuthException("Failed to get token from Renren: " + jsonObject); throw new AuthException("Failed to get token from Renren: " + jsonObject);
} }
......
...@@ -4,11 +4,11 @@ import cn.hutool.http.HttpRequest; ...@@ -4,11 +4,11 @@ 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.enums.AuthUserGender;
import me.zhyd.oauth.exception.AuthException; import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthCallback; 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.enums.AuthUserGender;
import me.zhyd.oauth.utils.UrlBuilder; import me.zhyd.oauth.utils.UrlBuilder;
import static me.zhyd.oauth.config.AuthSource.STACK_OVERFLOW; import static me.zhyd.oauth.config.AuthSource.STACK_OVERFLOW;
...@@ -35,9 +35,7 @@ public class AuthStackOverflowRequest extends AuthDefaultRequest { ...@@ -35,9 +35,7 @@ public class AuthStackOverflowRequest extends AuthDefaultRequest {
.form(parseQueryToMap(accessTokenUrl)) .form(parseQueryToMap(accessTokenUrl))
.execute(); .execute();
JSONObject accessTokenObject = JSONObject.parseObject(response.body()); JSONObject accessTokenObject = JSONObject.parseObject(response.body());
if (!response.isOk()) { this.checkResponse(accessTokenObject);
throw new AuthException("Unable to get token from Stack Overflow using code [" + authCallback.getCode() + "]: " + accessTokenObject);
}
return AuthToken.builder() return AuthToken.builder()
.accessToken(accessTokenObject.getString("access_token")) .accessToken(accessTokenObject.getString("access_token"))
...@@ -53,7 +51,9 @@ public class AuthStackOverflowRequest extends AuthDefaultRequest { ...@@ -53,7 +51,9 @@ public class AuthStackOverflowRequest extends AuthDefaultRequest {
.queryParam("key", this.config.getStackOverflowKey()) .queryParam("key", this.config.getStackOverflowKey())
.build(); .build();
HttpResponse response = HttpRequest.get(userInfoUrl).execute(); HttpResponse response = HttpRequest.get(userInfoUrl).execute();
JSONObject userObj = JSONObject.parseObject(response.body()).getJSONArray("items").getJSONObject(0); JSONObject object = JSONObject.parseObject(response.body());
this.checkResponse(object);
JSONObject userObj = object.getJSONArray("items").getJSONObject(0);
return AuthUser.builder() return AuthUser.builder()
.uuid(userObj.getString("user_id")) .uuid(userObj.getString("user_id"))
...@@ -77,4 +77,15 @@ public class AuthStackOverflowRequest extends AuthDefaultRequest { ...@@ -77,4 +77,15 @@ public class AuthStackOverflowRequest extends AuthDefaultRequest {
.queryParam("scope", "read_inbox") .queryParam("scope", "read_inbox")
.build(); .build();
} }
/**
* 检查响应内容是否正确
*
* @param object 请求响应内容
*/
private void checkResponse(JSONObject object) {
if (object.containsKey("error")) {
throw new AuthException(object.getString("error_description"));
}
}
} }
...@@ -4,11 +4,11 @@ import cn.hutool.http.HttpResponse; ...@@ -4,11 +4,11 @@ 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.enums.AuthUserGender;
import me.zhyd.oauth.exception.AuthException; import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthCallback; 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.enums.AuthUserGender;
import me.zhyd.oauth.utils.UrlBuilder; import me.zhyd.oauth.utils.UrlBuilder;
/** /**
...@@ -28,10 +28,7 @@ public class AuthTencentCloudRequest extends AuthDefaultRequest { ...@@ -28,10 +28,7 @@ public class AuthTencentCloudRequest extends AuthDefaultRequest {
protected AuthToken getAccessToken(AuthCallback authCallback) { protected AuthToken getAccessToken(AuthCallback authCallback) {
HttpResponse response = doGetAuthorizationCode(authCallback.getCode()); HttpResponse response = doGetAuthorizationCode(authCallback.getCode());
JSONObject accessTokenObject = JSONObject.parseObject(response.body()); JSONObject accessTokenObject = JSONObject.parseObject(response.body());
if (accessTokenObject.getIntValue("code") != 0) { this.checkResponse(accessTokenObject);
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"))
...@@ -43,9 +40,8 @@ public class AuthTencentCloudRequest extends AuthDefaultRequest { ...@@ -43,9 +40,8 @@ public class AuthTencentCloudRequest extends AuthDefaultRequest {
protected AuthUser getUserInfo(AuthToken authToken) { protected AuthUser getUserInfo(AuthToken authToken) {
HttpResponse response = doGetUserInfo(authToken); HttpResponse response = doGetUserInfo(authToken);
JSONObject object = JSONObject.parseObject(response.body()); JSONObject object = JSONObject.parseObject(response.body());
if (object.getIntValue("code") != 0) { this.checkResponse(object);
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"))
...@@ -63,6 +59,17 @@ public class AuthTencentCloudRequest extends AuthDefaultRequest { ...@@ -63,6 +59,17 @@ public class AuthTencentCloudRequest extends AuthDefaultRequest {
.build(); .build();
} }
/**
* 检查响应内容是否正确
*
* @param object 请求响应内容
*/
private void checkResponse(JSONObject object) {
if (object.getIntValue("code") != 0) {
throw new AuthException(object.getString("msg"));
}
}
/** /**
* 返回认证url,可自行跳转页面 * 返回认证url,可自行跳转页面
* *
......
...@@ -5,11 +5,11 @@ import com.alibaba.fastjson.JSONObject; ...@@ -5,11 +5,11 @@ 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.enums.AuthToutiaoErrorCode; import me.zhyd.oauth.enums.AuthToutiaoErrorCode;
import me.zhyd.oauth.enums.AuthUserGender;
import me.zhyd.oauth.exception.AuthException; import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthCallback; 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.enums.AuthUserGender;
import me.zhyd.oauth.utils.UrlBuilder; import me.zhyd.oauth.utils.UrlBuilder;
/** /**
...@@ -30,10 +30,7 @@ public class AuthToutiaoRequest extends AuthDefaultRequest { ...@@ -30,10 +30,7 @@ public class AuthToutiaoRequest extends AuthDefaultRequest {
HttpResponse response = doGetAuthorizationCode(authCallback.getCode()); HttpResponse response = doGetAuthorizationCode(authCallback.getCode());
JSONObject accessTokenObject = JSONObject.parseObject(response.body()); JSONObject accessTokenObject = JSONObject.parseObject(response.body());
if (accessTokenObject.containsKey("error_code")) { this.checkResponse(accessTokenObject);
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"))
...@@ -48,9 +45,7 @@ public class AuthToutiaoRequest extends AuthDefaultRequest { ...@@ -48,9 +45,7 @@ public class AuthToutiaoRequest extends AuthDefaultRequest {
JSONObject userProfile = JSONObject.parseObject(userResponse.body()); JSONObject userProfile = JSONObject.parseObject(userResponse.body());
if (userProfile.containsKey("error_code")) { this.checkResponse(userProfile);
throw new AuthException(AuthToutiaoErrorCode.getErrorCode(userProfile.getIntValue("error_code")).getDesc());
}
JSONObject user = userProfile.getJSONObject("data"); JSONObject user = userProfile.getJSONObject("data");
...@@ -89,7 +84,7 @@ public class AuthToutiaoRequest extends AuthDefaultRequest { ...@@ -89,7 +84,7 @@ public class AuthToutiaoRequest extends AuthDefaultRequest {
/** /**
* 返回获取accessToken的url * 返回获取accessToken的url
* *
* @param code * @param code 授权码
* @return 返回获取accessToken的url * @return 返回获取accessToken的url
*/ */
@Override @Override
...@@ -105,7 +100,7 @@ public class AuthToutiaoRequest extends AuthDefaultRequest { ...@@ -105,7 +100,7 @@ public class AuthToutiaoRequest extends AuthDefaultRequest {
/** /**
* 返回获取userInfo的url * 返回获取userInfo的url
* *
* @param authToken * @param authToken 用户授权后的token
* @return 返回获取userInfo的url * @return 返回获取userInfo的url
*/ */
@Override @Override
...@@ -115,4 +110,16 @@ public class AuthToutiaoRequest extends AuthDefaultRequest { ...@@ -115,4 +110,16 @@ public class AuthToutiaoRequest extends AuthDefaultRequest {
.queryParam("access_token", authToken.getAccessToken()) .queryParam("access_token", authToken.getAccessToken())
.build(); .build();
} }
/**
* 检查响应内容是否正确
*
* @param object 请求响应内容
*/
private void checkResponse(JSONObject object) {
if (object.containsKey("error_code")) {
throw new AuthException(AuthToutiaoErrorCode.getErrorCode(object.getIntValue("error_code"))
.getDesc());
}
}
} }
...@@ -118,7 +118,7 @@ public class AuthWeChatRequest extends AuthDefaultRequest { ...@@ -118,7 +118,7 @@ public class AuthWeChatRequest extends AuthDefaultRequest {
/** /**
* 返回获取accessToken的url * 返回获取accessToken的url
* *
* @param code * @param code 授权码
* @return 返回获取accessToken的url * @return 返回获取accessToken的url
*/ */
@Override @Override
...@@ -134,7 +134,7 @@ public class AuthWeChatRequest extends AuthDefaultRequest { ...@@ -134,7 +134,7 @@ public class AuthWeChatRequest extends AuthDefaultRequest {
/** /**
* 返回获取userInfo的url * 返回获取userInfo的url
* *
* @param authToken * @param authToken 用户授权后的token
* @return 返回获取userInfo的url * @return 返回获取userInfo的url
*/ */
@Override @Override
...@@ -147,10 +147,10 @@ public class AuthWeChatRequest extends AuthDefaultRequest { ...@@ -147,10 +147,10 @@ public class AuthWeChatRequest extends AuthDefaultRequest {
} }
/** /**
* 返回获取accessToken的url * 返回获取userInfo的url
* *
* @param refreshToken * @param refreshToken getAccessToken方法返回的refreshToken
* @return 返回获取accessToken的url * @return 返回获取userInfo的url
*/ */
@Override @Override
protected String refreshTokenUrl(String refreshToken) { protected String refreshTokenUrl(String refreshToken) {
......
...@@ -5,11 +5,11 @@ import cn.hutool.http.HttpResponse; ...@@ -5,11 +5,11 @@ 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.enums.AuthUserGender;
import me.zhyd.oauth.exception.AuthException; import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthCallback; 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.enums.AuthUserGender;
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; import me.zhyd.oauth.utils.UrlBuilder;
...@@ -34,8 +34,7 @@ public class AuthWeiboRequest extends AuthDefaultRequest { ...@@ -34,8 +34,7 @@ public class AuthWeiboRequest extends AuthDefaultRequest {
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 throw new AuthException(accessTokenObject.getString("error_description"));
.getString("error_description"));
} }
return AuthToken.builder() return AuthToken.builder()
.accessToken(accessTokenObject.getString("access_token")) .accessToken(accessTokenObject.getString("access_token"))
......
package me.zhyd.oauth.utils;
import org.junit.Test;
/**
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @version 1.0
* @website https://www.zhyd.me
* @date 2019/7/19 15:52
* @since 1.8
*/
public class CustomTest {
/**
* 1000000: 23135ms
* 100000: 3016ms
* 10000: 328ms
* 1000: 26ms
*/
@Test
public void test() {
long start = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
callMethod();
}
long end = System.currentTimeMillis();
System.out.println((end - start) + "ms");
}
/**
* 1000000: 19058ms
* 100000: 2772ms
* 10000: 323ms
* 1000: 29ms
*/
@Test
public void test2() {
long end = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
callMethod2();
}
long end2 = System.currentTimeMillis();
System.out.println((end2 - end) + "ms");
}
public String callMethod() {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
// for (StackTraceElement stackTraceElement : stackTrace) {
// System.out.println(stackTraceElement.getMethodName());
// }
return stackTrace[2].getMethodName();
}
public String callMethod2() {
StackTraceElement[] stackTrace = (new Throwable()).getStackTrace();
// for (StackTraceElement stackTraceElement : stackTrace) {
// System.out.println(stackTraceElement.getMethodName());
// }
return stackTrace[2].getMethodName();
}
}
...@@ -17,11 +17,12 @@ import org.junit.Test; ...@@ -17,11 +17,12 @@ import org.junit.Test;
public class UrlBuilderTest { public class UrlBuilderTest {
@Test @Test
public void testUrlBuilder() { public void testUrlBuilder() {
AuthConfig config = new AuthConfig(); AuthConfig config = AuthConfig.builder()
config.setClientId("appid-110110110"); .clientId("appid-110110110")
config.setClientSecret("secret-110110110"); .clientSecret("secret-110110110")
config.setRedirectUri("https://xkcoding.com"); .redirectUri("https://xkcoding.com")
config.setState(AuthState.create(AuthSource.WECHAT)); .state(AuthState.create(AuthSource.WECHAT))
.build();
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())
......
...@@ -6,6 +6,8 @@ ...@@ -6,6 +6,8 @@
4. 优化百度授权流程,增加refresh token的方法 4. 优化百度授权流程,增加refresh token的方法
5. 优化`AuthConfig``AuthResponse`类,去掉不必要的lombonk注解,减少编译后的代码量 5. 优化`AuthConfig``AuthResponse`类,去掉不必要的lombonk注解,减少编译后的代码量
6. 使用lombok注解优化枚举类 6. 使用lombok注解优化枚举类
7. `AuthQqRequest`增加refresh方法
8. 优化代码
### 2019/07/18 ### 2019/07/18
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册